Leetcode-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

思路:DP

1.如果p结束的时候,s必须结束,否则false;
2.*(p+1)=='*'的情况:*p为'.'或者*p==*s 循环到s的结尾;
3.*(p+1)不是'*'的情况,逐字检查就好。

AC code:
bool isMatch(char* s, char* p) {
    if(s==NULL||p==NULL)
    return false;
    
    if(*p=='\0') return *s=='\0';
    
    if(*(p+1)=='*')
    {
        while(*s!='\0'&&*p=='.'||*s==*p)
        {
            if(isMatch(s,p+2))
            return true;
            s++;
        }
        
        return isMatch(s,p+2);
    }
    else if((*s!='\0'&&*p=='.')||*s==*p)
    {
        return isMatch(s+1,p+1);
    }
    
    return false;
}

 

posted @ 2016-08-07 17:29  Pacific-hong  阅读(71)  评论(0编辑  收藏  举报