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);
}
}
};
[LeetCode] Regular Expression Matching,布布扣,bubuko.com
[LeetCode] Regular Expression Matching
原文:http://blog.csdn.net/swagle/article/details/28407559