正则表达式匹配

class Solution {
public:
    bool isMatch(string s, string p) {
        int m=s.size(),n=p.size();
        vector<vector<bool>> dp(m+1,vector<bool>(n+1,false));

        dp[0][0]=true;
        //init row
        for(int j=1;j<n+1;j++){
            if(j>1 && dp[0][j-2]==true && p[j-1]=='*'){
                dp[0][j]=true;
            }
        }

        //init col

        for(int i=1;i<m+1;i++){
            for(int j=1;j<n+1;j++){
                if(s[i-1]==p[j-1] || p[j-1]=='.'){
                    dp[i][j]=dp[i-1][j-1];
                }
                else if(p[j-1]=='*'){
                    if(s[i-1]!=p[j-2] && p[j-2]!='.'){
                        dp[i][j]=dp[i][j-2];
                    }
                    else{
                        dp[i][j]=dp[i][j-2] || dp[i][j-1] || dp[i-1][j];
                    }
                }
            }
        }
        return dp[m][n];

    }
};
posted @ 2020-03-07 16:16  7aughing  阅读(201)  评论(0编辑  收藏  举报