[LeetCode] Regular Expression Matching [6]
2014-06-04 12:09
435 查看
题目:
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 )
相关文章推荐
- LeetCode Regular Expression Matching
- LeetCode_Regular Expression Matching
- leetcode第10题——***Regular Expression Matching
- [LeetCode]Regular Expression Matching
- Regular Expression Matching -- leetcode
- [Leetcode] Regular Expression Matching
- leetcode-010:Regular Expression Matching
- leetcode 10: Regular Expression Matching
- LeetCode(10) Regular Expression Matching
- leetcode_c++: Regular Expression Matching(010)
- LeetCode: Regular Expression Matching
- Leetcode -- Regular Expression Matching
- LeetCode: Regular Expression Matching
- LeetCode--Regular Expression Matching 正则表达式匹配
- Regular Expression Matching [leetcode]
- [leetcode]Regular Expression Matching
- 【leetcode】 Regular Expression Matching
- [LeetCode][JavaScript]Regular Expression Matching
- 【leetcode】第10题 Regular Expression Matching 题目+解析+代码
- leetcode 10 Regular Expression Matching