leetcode刷题正则表达式

题目链接:https://leetcode-cn.com/problems/regular-expression-matching/

这道题用到了动态规划:

关于动态规划请参考这篇博文:https://blog.csdn.net/u013309870/article/details/75193592

写的非常详细。

在做题过程中我参考了leetcode上某大佬的文章https://leetcode.com/problems/regular-expression-matching/discuss/5684/9-lines-16ms-c-dp-solutions-with-explanations

大概思想就是我们在建立解题模型时,分情况考虑对象的匹配规则,即:p[j-1]==’*’和其他情况,

然后在分别加以记录就可以了,但是我们开始建立的是bool型的容器,所以需要考虑相应点的bool变量的表示

ifp[j-1]==’*’s{cur[j-1]=cur[j-2]||(i&&cur[j]&&(s[i-1]==p[j-2]||p[j-1==’.’]));}

else{cur[i]=i&&pre&&(s[i-1]==p[j-1]||p[j-1]==’.’)}

最后再进行返回即可,完整c++版代码如下:

class Solution {
public:
    bool isMatch(string s, string p) {
        int m=s.size(),n=p.size();
        vector<bool> cur(n+1,false);
        for(int i=0;i<=m;i++)
        {
            bool pre=cur[0];
            cur[0]=!i;
            for(int j=1;j<=n;j++)
            {
                bool temp=cur[j];
                if(p[j-1]=='*')
                {
                    
                    cur[j]=cur[j-2]||(i&&cur[j]&&(s[i-1]==p[j-2]||p[j-2]=='.')) ;
                }
                else
                {
                    cur[j]=i&&pre&&(s[i-1]==p[j-1]||p[j-1]=='.');
                }
                pre=temp;
            }
            
            
        }
        return cur[n];        
    }
};
posted @ 2019-04-18 21:19  kailicard  阅读(240)  评论(0编辑  收藏  举报