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

代碼:

bool isMatch(char* s, char* p) {
    if( *p == '\0' )
        return *s == '\0';
        
    if( *( p + 1 ) != '*' )
    {
        if( *p == *s || ( *p == '.' && *s != '\0' ) )
            return isMatch( s + 1, p + 1 );
        return false;
    }
    else
    {
        while( *p == *s || ( *p == '.' && *s != '\0' ) )  //實現*的擴展
        {
            if( isMatch( s, p + 2 ) )  //需要跳過*來比較後面的p+2字符串
                return true;
            s++;  //保證了s, s+1都是重複的,類似於*擴展作用
        }
        return isMatch( s, p + 2 );
    }
}

1)這道題目的思路可以動態規劃,解題思路可以參考:

http://blog.csdn.net/tingmei/article/details/8049850     

http://blog.csdn.net/doc_sgl/article/details/12719761

http://my.oschina.net/jdflyfly/blog/283584

根據下一個字符是否是'*'分情況判斷。
如果p的下一個字符不是'*',只需判斷當前字符是否相等,或者p[cur]='.',遞歸處理s[i+1]和p[j+1];
如果是p的下一個'*',則當前s和p相等或者p='.'情況下,依次判斷s[0...s.length]和p2]是否match;程序中這部分使用while循環來實現‘*’的擴展功能



2)char數組判斷結尾可以使用\0,也可以使用0;






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