66. Regular Expression Matching
2014-09-08 12:19
375 查看
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 思路: 这题 ugly 之处,在于 '*' 给的很不明朗, 其实'c*', 表示 '*' 可以代表 'ccc...cc'。 对 '*' 的理解,若出现 p中出现 '*', 则要比较用 s 和 p 中 '*' 之前的那个元素比较,从左往右找出 s 中第一个与 p 之前的元素不同的元素。 (若全相同,例如, 之前那个元素为 '.', 则 '.*' (表示'.......^....')可以匹配任何 s 串)。
//垃圾题!rubbish question! class Solution { public: bool isMatch(const char *s, const char *p) { if (s == NULL || p == NULL) return false; if (*p == '\0') return *s == '\0'; // ".*" matches "", so we can't check (*s == '\0') here. if (*(p + 1) == '*'){ // Here *p != '\0', so this condition equals with // (*s != '\0' && (*p == '.' || *s == *p)). while ((*s != '\0' && *p == '.') || *s == *p){ if (isMatch(s, p + 2)) return true; ++s; } return isMatch(s, p + 2); } else if ((*s != '\0' && *p == '.') || *s == *p){ return isMatch(s + 1, p + 1); } return false; } };
相关文章推荐
- Regular Expression Matching
- LeetCode Regular Expression Matching
- LeetCode OJ:Regular Expression Matching(正则表达式匹配)
- [LeetCode] Regular Expression Matching, Solution
- leetcode 10 Regular Expression Matching
- LintCode_154 Regular Expression Matching
- leetcode_c++: Regular Expression Matching(010)
- Hard 10题 Regular Expression Matching
- leetcode解题笔记:Regular Expression Matching
- Regular Expression Matching(LeedCode)
- LeetCode——Regular Expression Matching
- LeetCode010 Regular Expression Matching 解析
- LeetCode (10)Regular Expression Matching
- Leetcode 10. Regular Expression Matching
- LeetCode: Regular Expression Matching
- Regular Expression Matching
- LeetCode正则表达式-Regular Expression Matching
- [LeetCode] Regular Expression Matching
- Leetcode_regular-expression-matching
- [DP] LeetCode Regular Expression Matching