[LeetCode] Regular Expression Matching [6]

称号:

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

原题地址

解题思路

设计一个支持‘.' 和 '*' 的正則表達式匹配算法。


这个题复杂的地方在于对于 '*' 的处理。这个符号在正則表達式中被称为贪婪型的量词。这个量词在实际匹配过程中也是尽可能多的匹配直到词尾或者不匹配成功才结束。然后假设其后面还有没有匹配的,则回退到合适的位置。然后才进行下一个匹配。

正則表達式中的匹配优先与回溯大概也就是这个意思。关于正則表達式这方面的知识。有兴趣能够读读《精通正則表達式》的第4章表达式的匹配原理。
回到本题,正由于 '*'的特殊性。我们在分类的时候选择依据 '*' 来进行,分类后其子问题也是一个正則表達式匹配的问题。所以这能够使用递归来做。以下来看看代码,代码中有凝视说明匹配的类型:

代码实现:

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) != '*'){
            if(*p==*s || (*p=='.' && *s!='\0'))
                return isMatch(s+1, p+1);
            return false;
        }
        else{
            //s="aaaabbbb", p="a.*b"
            while(*p==*s || (*p=='.' && *s!='\0')){
                if(isMatch(s, p+2))
                    return true;
                ++s;
            }
            //s="ab", p="aa*b"
            return isMatch(s, p+2);
        }
    }
};
假设你认为本篇对你有收获,请帮顶。


另外,我开通了微信公众号--分享技术之美,我会不定期的分享一些我学习的东西.

你能够搜索公众号:swalge 或者扫描下方二维码关注我

(转载文章请注明出处: http://blog.csdn.net/swagle/article/details/28407559 )

版权声明:本文博主原创文章,博客,未经同意不得转载。

posted @ 2015-10-03 10:58  zfyouxi  阅读(196)  评论(0编辑  收藏  举报