leetcode第十題--Regular Expression Matching

Problem: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正則表達式

就是正則表達式,能夠百度一下先學習什麼事正則表達式。*號是表示前面一個字符出現零次或者屢次。例如 zo*能和z匹配是由於此處*表示前面的字符o出現零次,因此和z匹配,同理,zo*還能夠和zo或者zoo,zoooo,zooooooooo等等匹配。點‘.’是通配符,匹配任意一個單字符。那麼點星‘.*’就能夠匹配任意多個字符,由於*表示前面的任意多個重複。因此就是任意多個‘.’的重複,而‘.’又是任意匹配,因此就是任意組合均可以。第一個點匹配a第二個點並非只能匹配a,仍是能夠匹配任意的字符。因此‘.*’確實是萬能的。應該沒有理解錯誤吧。 而後這題,考慮了好久,都沒有想到好的思路,不得不用遞歸。express

class Solution {
public:
bool isMatch(const char *s, const char *p)
{
    if(s == NULL || p == NULL)
        return false;
    if (*p == '\0')
        return *s == '\0';

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

提交嘗試好屢次把 if (*p == '\0') return *s == '\0'; 忽略。由於是遞歸的,因此不能沒有。這裏的'.'不能對應‘\0’less

也能夠參考這位同窗的。學習

相關文章
相關標籤/搜索