120_leetcode_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

1:注意特殊情況;2:採用遞歸;3:分爲*(p + 1) = '*‘和*(p + 1) != '*‘兩種情況;

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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章