LeetCode | Regular Expression Matching
2014-05-07 15:00
417 查看
Regular Expression Matching
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
思路是分别处理a*、.*、.、a的情况。
三周前写的lengthy code如下:
class Solution { public: bool isMatch(const char *s, const char *p) { int sn = strlen(s); int pn = strlen(p); return recursive(s, sn, p, pn); } bool recursive(const char* s, int sn, const char* p, int pn) { if (sn == 0 && pn == 0) return true; if (pn == 0) return false; if (*(p + 1) != '\0') { if (*(p + 1) == '*') { if (*p == '.') { // .* int n = 0; while (n <= sn) { if (recursive(s + n, sn - n, p + 2, pn - 2)) return true; n++; } } else { // a* int n = 0; while (n <= sn && *(s + n) == *p) { if (recursive(s + n, sn - n, p + 2, pn - 2)) return true; n++; } if (recursive(s + n, sn - n, p + 2, pn - 2)) return true; } } else { if (*p != '.' && *s != *p) return false; if (recursive(s + 1, sn - 1, p + 1, pn - 1)) return true; } } else { if (*p != '.' && *s != *p) return false; if (recursive(s + 1, sn - 1, p + 1, pn - 1)) return true; } } };
今天看了Leetcode上1337的代码真是羞愧啊。http://leetcode.com/2011/09/regular-expression-matching.html
重写了一遍。思路还是一样。
class Solution { public: bool isMatch(const char *s, const char *p) { if (*p == '\0') return (*s == '\0'); // match single '\0', '.', 'a'... if (*(p + 1) != '*') { return ((*s == *p || (*p == '.' && *s != '\0')) && isMatch(s + 1, p + 1)); } // match a*, .* while ((*s == *p || (*p == '.' && *s != '\0'))) { if (isMatch(s++, p + 2)) return true; } // ignore a*, *p != '.' && *s != *p return isMatch(s, p + 2); } };
相关文章推荐
- LeetCode题解: Regular Expression Matching
- leetcode Regular Expression Matching
- LeetCode – Regular Expression Matching in Java
- leetcode 10 Regular Expression Matching(简单正则表达式匹配)
- [LeetCode]-010-Regular Expression Matching
- LeetCode 10 - Regular Expression Matching
- [leetcode 10] Regular Expression Matching
- Leetcode Regular Expression Matching
- LeetCode 10 Regular Expression Matching (正则表达式匹配)
- LeetCode_10 Regular Expression Matching
- LeetCode_Regular Expression Matching
- [LeetCode]010-Regular Expression Matching
- LeetCode - 10. Regular Expression Matching
- LeetCode Regular Expression Matching
- leetcode-010:Regular Expression Matching
- 【LeetCode笔记】Wildcard Matching 和 Regular Expression Matching
- LeetCode Problem10 Regular Expression Matching
- [LeetCode] Regular Expression Matching 解题报告
- LeetCode: Regular Expression Matching
- LeetCode: Regular Expression Matching