[Leetcode] Regular Expression Matching
来源:互联网 发布:深圳淘宝运营助理招聘 编辑:程序博客网 时间:2024/05/15 03:59
题目:
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") → falseisMatch("aa","aa") → trueisMatch("aaa","aa") → falseisMatch("aa", "a*") → trueisMatch("aa", ".*") → trueisMatch("ab", ".*") → trueisMatch("aab", "c*a*b") → true
思路:又是一道很恶心的题,尽管代码写出来很简洁。之所以使用递归是因为*的情况需要回溯,虽然也可以使用两个指针记录回溯位置,但是递归写起来比较简洁 —— 只需要考虑当前状态的匹配情况,然后将后面的判断交给下一层函数进行处理。
需要考虑的匹配项有:若对应字符相等或p的字符为'.',可以直接匹配,同时要判断当p的字符为'.'时,s必须有一个字符可以去匹配,不能为空;当p+1为*字符时,需要判断*对应多个字符的所有情况。
class Solution {public: bool isMatch(const char *s, const char *p) { if (*p == '\0') return *s == '\0'; if (*(p + 1) != '*') { return (*s == *p || (*p == '.' && *s != '\0')) && isMatch(s + 1, p + 1); } else { while (*s != '\0' && (*s == *p || *p == '.')) { if (isMatch(s, p + 2)) return true; s++; } return isMatch(s, p + 2); } }};
总结:复杂度为O(mn),最坏情况可能需要不断回溯。
0 0
- 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
- AlipayRsaLib.a(base64.o) ld: 2 duplicate symbols for architecture i386
- 荣耀A55高调上市只为孤独求败?
- 优化Android App性能?十大技巧必知!
- JLINK调试问题总结
- 微博里很多明星的自拍照好老好丑,他们怎么这么自信PO上去的?娱乐八卦天涯论坛
- [Leetcode] Regular Expression Matching
- Linux-C实现GPRS模块发送短信
- Object-C 入门 Xcode 环境详解
- 抛弃儿子放在寺院的明星早就被人8出来了,八卦er还没8出来娱乐八卦天涯论坛
- 看到满屏的锥子脸,姐大吼一声:姐就是喜欢大饼脸就是喜欢大饼脸娱乐八卦天涯论坛
- stanford machine learning, linear regression
- OpenGL+VS2013+WIN7(64)配置
- 漫谈事务与分布式事务(4)- 最终一致性
- 黎姿双胞胎女儿周岁庆生 举家庆祝模样曝光(图)娱乐八卦天涯论坛