10. Regular Expression Matching 字符串匹配 左程云


Implement regular expression matching with support for '.' and '*'.

'.' Matches any single character.
'*' Matches zero or more of the preceding element.

The matching should cover the entire input string (not partial).

The function prototype should be:
bool isMatch(const char *s, const char *p)

Some examples:
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "a*") → true
isMatch("aa", ".*") → true
isMatch("ab", ".*") → true
isMatch("aab", "c*a*b") → true
class Solution {
public:
    bool isMatch(string s, string p) {
        return process(s,p,0,0);
    }
    bool process(string& s,string& p,int si,int pi){
        if(pi==p.size())//到结尾了,另一个也必须到结尾
            return si==s.size();
        //当前匹配下一个字符不是‘*’
        if(pi==p.size()-1||p[pi+1]!='*')
            return si!=s.size()&&(s[si]==p[pi]||p[pi]=='.')&&process(s,p,si+1,pi+1);
        //后一个字符是'*'
        while(si!=s.size()&&(p[pi]==s[si]||p[pi]=='.'))
        {
            if(process(s,p,si,pi+2))
                return true;
            si++;
        }
        return process(s,p,si,pi+2);
        
        
    }
};

动态规划解法:

class Solution {
public:
    bool isMatch(string s, string p) {
        vector<vector<bool>> dp(s.size()+1,vector<bool>(p.size()+1,false));//建立动归属组
        //因为当前的值跟后面的多行和固定的后两列有关,所以需要预先确定最后一行和倒数第1、2列
        int sr=s.size();
        int pr=p.size();
        dp[sr][pr]=true;
        
        for(int i=pr-2;i>=0;i-=2)
        {
            if(p[i]!='*'&&p[i+1]=='*')
            dp[sr][i]=true;
            else 
                break;//遇到一个不行的其他的就都不行
        }
        //倒数第一列都是false
        //倒数第二列,只有sr只剩一个的时候可能相等
        
        if(sr>0&&pr>0)
        {
            if(s[sr-1]==p[pr-1]||p[pr-1]=='.')
            dp[sr-1][pr-1]=true;
        }
        //下面是正式的一般情况的
        for(int i=sr-1;i>=0;i--)
            for(int j=pr-2;j>=0;j--)
            {
                if(p[j+1]!='*')
                {
                    dp[i][j]=(s[i]==p[j]||p[j]=='.')&&dp[i+1][j+1];
                }
                else
                {
                    int si=i;
                    while(si!=s.size()&&(p[j]==s[si]||p[j]=='.'))
                    {
                        if(dp[si][j+2]) 
                        {
                            dp[i][j]=true;
                            break;
                        }
                        si++;
                    }
                    if(dp[i][j]!=true)
                        dp[i][j]=dp[si][j+2];
                }
            }
        return dp[0][0];


        
        
    }
};



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值