您的位置:首页 > 其它

leetcode-10 Regular Expression Matching

2016-03-25 16:30 501 查看
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


http://blog.csdn.net/doc_sgl/article/details/12719761

判断第二个串中是否匹配第一个
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
//////////////////////////////////////////////////////////////////////////

扩展情况:

http://www.cnblogs.com/felixfang/p/3708999.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: