30. 正则表达式匹配

正则表达式

class Solution {
public:
    int n,m;
    vector<vector<int>>dp;
    bool isMatch(string s, string p) {
        n = s.size();
        m = p.size();
        dp = vector<vector<int>> (n + 1, vector<int>(m + 1, -1));
        return isMatch(0, 0, s, p) || (n ==0 && m == 0);
    }
    bool isMatch(int x, int y, string &s, string &p){
        if(dp[x][y] != -1)//记忆化
            return dp[x][y];
        if(y == m)
            return dp[x][y] = x == n;//边界
        bool firstMatch = (x < n && (s[x] == p[y] || p[y] == '.'));
        bool ans;
        if(y + 1 < m && p[y + 1] == '*'){
            ans = (firstMatch && isMatch(x+1,y,s,p)) || isMatch(x,y+2,s,p);// 1次(包括1次)以上或者0次 
        }
        else{
            ans = firstMatch && isMatch(x+1,y+1,s,p); //直接匹配下一个
        }
        return ans;
    }
};
posted @ 2020-07-20 10:28  hh13579  阅读(122)  评论(0)    收藏  举报