Leetcode 10. Regular Expression Matching

Posted ximelon

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 10. Regular Expression Matching相关的知识,希望对你有一定的参考价值。

https://leetcode.com/problems/regular-expression-matching/

class Solution {
public:
    bool isMatch(string s, string p) {
        /*
        动态规划问题:
        dp[i][j]代表s[0...i-1],和p[0...j-1]是否匹配
        p[j-1]=='.'时,dp[i][j]=dp[i-1][j-1]
        p[j-1]=='*'时,dp[i][j]=dp[i][j-2] | (dp[i-1][j] & (p[j-2]=='.' | s[i-1]==p[j-2]))对应0字符、有字符
        其他情况,dp[i][j]=dp[i-1][j-1] & s[i-1]==p[j-1]
        */
        const int Ls=s.size(),Lp=p.size();
        
        bool dp[Ls+1][Lp+1];
        dp[0][0]=true;
        for(int j=1;j<=Lp;++j){
            if(p[j-1]=='*')
                dp[0][j]=dp[0][j-2];
            else
                dp[0][j]=false;
        }
        for(int i=1;i<=Ls;++i){
            dp[i][0]=false;
            for(int j=1;j<=Lp;++j){
                if(p[j-1]=='.')
                    dp[i][j]=dp[i-1][j-1];
                else if(p[j-1]=='*')
                    dp[i][j]=dp[i][j-2] | (dp[i-1][j] & (p[j-2]=='.' | s[i-1]==p[j-2]));
                else
                    dp[i][j]=dp[i-1][j-1] & s[i-1]==p[j-1];
            }
        }
        return dp[Ls][Lp];
    }
};

以上是关于Leetcode 10. Regular Expression Matching的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 10. Regular Expression Matching

leetcode 10. Regular Expression Matching

Leetcode 10: Regular Expression Matching

[LeetCode #10] Regular Expression Matching

[LeetCode] 10. Regular Expression Matching ☆☆☆☆☆

leetcode-10. Regular Expression Matching