【LeetCode】10. Regular Expression Matching

Regular Expression Matchinghtml

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

'.' 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

 

比较与Wildcard Matching的关系。spa

Wildcard Matching中的'?'与此题的'.'一致。prototype

可是Wildcard Matching中'*'自己表明通配符,而此题'*'表明前一个字符重复0或若干次。code

解题过程以下:htm

一、考虑特殊状况即*s字符串或者*p字符串结束。blog

(1)*s字符串结束,要求*p也结束或者间隔‘*’ (例如*p="a*b*c*……"),不然没法匹配递归

(2)*s字符串未结束,而*p字符串结束,则没法匹配ip

二、*s字符串与*p字符串均未结束element

(1)*(p+1)字符不为'*',则只需比较*s字符与*p字符,若相等则递归到*(s+1)字符串与*(p+1)字符串的比较,不然没法匹配。

(2)*(p+1)字符为'*',则*p字符能够匹配*s字符串中从0开始任意多(记为i)等于*p的字符,而后递归到*(s+i+1)字符串与*(p+2)字符串的比较,

只要匹配一种状况就算彻底匹配。

class Solution {
public:
    bool isMatch(const char *s, const char *p) {
        //entire match
        if(*s == 0)
        {
            if(*p == 0 || (*(p+1) == '*' && isMatch(s,p+2)))
                return true;
            else
                return false;
        }
        else if(*p == 0)
            return false;

        if(*(p+1) != '*')
        {
            if(*s == *p || *p == '.')
                return isMatch(s+1, p+1);
            else
                return false;
        }
        else
        {
            if(*s != *p && *p != '.')
            {//try matches 0 char, skip p and p+1 ('*')
                return isMatch(s, p+2);
            }
            else
            {
                //try matches 0 char, skip p and p+1 ('*')
                if(isMatch(s, p+2))
                    return true;

                int i = 0;
                while(*(s+i) == *p || *p == '.')
                {//try all the length '*' matches
                    if(isMatch(s+i+1, p+2))
                        return true;
                    if(*(s+i+1) == 0)
                    //tried to end
                        break;
                    i ++;
                }
                return false;
            }
        }
    }
};

相关文章
相关标签/搜索