【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;
            }
        }
    }
};

相關文章
相關標籤/搜索