[LeetCode] Regular Expression matching
来源:互联网 发布:淘宝店招素材图 编辑:程序博客网 时间:2024/05/17 03:12
'.' 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") → falseisMatch("aa","aa") → trueisMatch("aaa","aa") → falseisMatch("aa", "a*") → trueisMatch("aa", ".*") → trueisMatch("ab", ".*") → trueisMatch("aab", "c*a*b") → true
Refer to: http://leetcode.com/2011/09/regular-expression-matching.html
The recursion mainly breaks down elegantly to the following two cases:
- If the next character of p is NOT ‘*’, then it must match the current character of s. Continue pattern matching with the next character of both s and p.
- If the next character of p is ‘*’, then we do a brute force exhaustive matching of 0, 1, or more repeats of current character of p… Until we could not match any more characters.
You would need to consider the base case carefully too. That would be left as an exercise to the reader.
class Solution {public: bool isMatch(const char *s, const char *p) { // Note: The Solution object is instantiated only once and is reused by each test case. assert(s&&p); //exit when s and p points to NULL //base case: if(*p=='\0') return *s=='\0'; if(*(p+1) != '\*') { //a strict matching assert( *p!='\*' ); //the start of p cannot be * if(*s==*p || (*p=='.' && *s!='\0') ) return isMatch(s+1,p+1); else return false; } else{ //recursively match different number(1~until *s and *p failed to match) of *p in s while( *s==*p || (*p=='.' && *s!='\0') ) { if(isMatch(s,p+2)) return true; //p+2 points to the next character after '*' s++; } } //fail to find a match with *, it means that in s, the number of "*p" is 0 return isMatch(s,p+2); }};
- LeetCode: Regular Expression Matching
- LeetCode: Regular Expression Matching
- 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: Regular Expression Matching
- [LeetCode] Regular Expression matching
- [LeetCode] Regular Expression Matching
- LeetCode Regular Expression Matching
- leetcode Regular Expression Matching
- leetcode: Regular Expression Matching
- LeetCode Regular Expression Matching
- Leetcode: Regular Expression Matching
- leetcode:Regular Expression Matching
- 对json的简单理解
- paip. 解决php 以及 python 连接access无效的参数量。参数不足,期待是 1”的错误
- 在CSDN的最后一篇博客
- (4)事件处理——(13)复合方法(Compound events)
- 【后缀表达式的计算思想、过程以及算法实现】
- [LeetCode] Regular Expression matching
- 通过MyEclipse 9.0对Liferay6.1.2进行编译与部署
- FFMPEG1.2 音频解码的过程
- 2013年 Lucene教程详解
- 读取bmp格式图片(二)
- 使用Dom4j解析XML
- axf elf 和bin 区别
- Error:有多个运算符"+="与这些操作数匹配
- cocos2d-x切换场景效果