LeetCode算法题目: Regular Expression Matching
2017-04-05 18:14
323 查看
题目:
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
分析:
场景1:a*ab “aaab”场景2:abac “ac”
用递归的方法来处理,对于x*,要处理有0到N个x被match下后剩下的递归匹配。
对于其他非x*的场景,直接匹配之后递归即可。
注意:当匹配串全部完成之后,如果模式串还有,查看一下剩下的模式串是不是可以匹配空字符串的即可,比如“abc*”的任意重复pair形式。
代码:
bool isMatch(const char *s, const char *p) { // Start typing your C/C++ solution below // DO NOT write int main() function if (*p == 0) return *s == 0; if (*(p+1) != '*') { if (*s != 0 && (*p == *s || *p == '.')) return isMatch(s+1, p+1); else return false; } else { // *s == *p while (*s != 0 && (*s == *p || *p == '.')) { if (isMatch(s, p+2)) return true; s++; } return (isMatch(s, p+2)); } }
相关文章推荐
- 【leetcode】第10题 Regular Expression Matching 题目+解析+代码
- python写算法题:leetcode: 10. Regular Expression Matching
- LeetCode题目解析(二):10、Regular Expression Matching
- LeetCode Online Judge 题目C# 练习 - Regular Expression Matching
- LeetCode -- Regular Expression Matching 【算法】
- LeetCode题目: 10. Regular Expression Matching
- leetcode: Regular Expression Matching
- [LeetCode]Regular Expression Matching、Wildcard Matching
- [leetcode]Regular Expression Matching
- leetcode-010:Regular Expression Matching
- LeetCode Regular Expression Matching
- leetcode Wildcard Matching ,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 - Recursively
- LeetCode 面试题 Regular expression matching(正则匹配)