leetcode-10 Regular Expression Matching

Implement regular expression matching with support for  '.'  and  '*' .
'.' Matches any single character.
'*' Matches zero or more of the preceding(前面的数字可以出现任意次,包括0次) element.
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
判断第二个串中是否匹配第一个
1.用 Recusion(递归)的方法
2.用 DP 的方法
   用数组 DP : dp[i][j] 表示 s[0..i] 和 p[0..j] 是否 match,当  p[j] != '*',dp [i + 1][j + 1] = dp[i][j] && s[i+1] == p[j+1] ,当 p[j] == '*' 要再分类讨论,还可以压缩下把 dp 降成一维。
   用记忆化,就是把算过的结果保存下来,下次就不用再算了。

///
// start: judge whether regular expression matching with '.' and '*'
/************************************************************************/
/* method1: DP                                                                                  */
/************************************************************************/
bool isMatch_DP(string s, string p) 
{
}

/************************************************************************/
/* method2: Recusion                                                                        */
/************************************************************************/
bool isMatch_Recusion(string s, string p)  // find match of s in p
{
    if(s[0] == '\0' && p[0] == '\0')
        return true;

    int slen = s.size(), plen = p.size();
    if(plen == 1 || p[1] != '*')  // p只有一个字符或者下一个不是'*'
    {
        return s[0] /*s可能空*/ && (p[0] == '.'  || s[0] == p[0] /*当前是否匹配*/) && isMatch_Recusion(s+1, p+1)/*后面是否匹配*/;
    }
    
    // p下一个是'*'
    while(s[0] /*s可能空*/ && (p[0] == '.'  || s[0] == p[0]))  / 若s[0]和p[0]相等,挨个略过
        if(isMatch_Recusion(s+1, p+2))
            return true;  
    return  isMatch_ Recusion(s, p+2);  // 当前字符不等,且下一个是'*',直接跳过两个
}
// end
//

扩展情况:
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值