10. Regular Expression Matching

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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

法I:回溯法。在下一个字符是*时 要进行backtrack。

class Solution {
public:
    bool isMatch(string s, string p) {
        return dfsIsMatch(s,p,0,0);
    }
    
    bool dfsIsMatch(const string& s, const string& p, int sIndex, int pIndex){
        if (p[pIndex] == \0) //结束条件:s若是‘\0‘,p必须也是‘\0‘
            return  s[sIndex] == \0;
        
        if (p[pIndex+1] == *) {
            /* ‘.‘ means any character (except ‘\0‘)
             * ‘.‘ means repeat 0 or more times
             * ‘.*‘ means repeat ‘.‘ 0 or more times
             */ 
            while ((s[sIndex] != \0 && p[pIndex] == .) || s[sIndex] == p[pIndex]) { //‘.‘可以与除‘\0‘以外的任何字符匹配
                if (dfsIsMatch(s, p, sIndex, pIndex+2)) //p[pIndex] repeat 0 times
                    return true;

                sIndex += 1;//p[pIndex]在原基础上repeat次数+1
            }
            
            return dfsIsMatch(s, p, sIndex, pIndex+2); //when s[sIndex] != p[pIndex] && p[pIndex] != ‘.‘(此时只有s[sIndex]==p[pIndex]==‘\0‘时可能return true)
        } 
        else if ((s[sIndex] != \0 && p[pIndex] == .) || s[sIndex] == p[pIndex]) {
            return dfsIsMatch(s, p, sIndex + 1, pIndex + 1);
        }
       
        return false;
    }
};

 

法II:动态规划。设二位数组dp[i][j]来表示两个string的状态关系,dp[i][j]=true,表示s[0..i]匹配p[0..j]的结果。

 

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

10. Regular Expression Matching

10. Regular Expression Matching

10. Regular Expression Matching

10. Regular Expression Matching

10 Regular Expression Matching

10. Regular Expression Matching