LeetCode : Regular Expression Matching
2014-06-19 23:14
375 查看
From : https://oj.leetcode.com/problems/regular-expression-matching/
Implement regular expression matching with support for
Let us rule the length of string s is l_s,and the length of string p is l_p;
It is easy to come up with an idea using Dynamic Programming, the time complexity of which is O(l_p*l_s). Use this method to solve this problem, and Time Limit Exceeded will be given by Online Judge.
Notice that "*" can match zero or more of the preceding element, the time complexity of enumeration is also O(l_s*l_p), but for the elements in string p which are not '*', the time complexity of transfer will be O(1), which
is the reason why enumeration use less time.
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
Let us rule the length of string s is l_s,and the length of string p is l_p;
It is easy to come up with an idea using Dynamic Programming, the time complexity of which is O(l_p*l_s). Use this method to solve this problem, and Time Limit Exceeded will be given by Online Judge.
Notice that "*" can match zero or more of the preceding element, the time complexity of enumeration is also O(l_s*l_p), but for the elements in string p which are not '*', the time complexity of transfer will be O(1), which
is the reason why enumeration use less time.
class Solution { public: bool isMatch(const char *s, const char *p){ if(!p[0]) return !s[0]; if(p[1]=='*'){ while(s[0]&&(s[0]==p[0]||p[0]=='.')){ if(isMatch(s,p+2)) return true; s++; } return isMatch(s,p+2); } else if(s[0]&&(s[0]==p[0]||p[0]=='.'))return isMatch(s+1,p+1); return false; } };
相关文章推荐
- LeetCode Regular Expression Matching
- leetcode 10: Regular Expression Matching 分析及解答
- LeetCode----10**. Regular Expression Matching
- [DP] LeetCode Regular Expression Matching
- [LeetCode] Regular Expression Matching, Solution
- leetcode解题报告:10 Regular Expression Matching
- [LeetCode]Regular Expression Matching
- Leetcode-Regular Expression Matching
- [leetcode] Regular Expression Matching
- LeetCode 10. Regular Expression Matching
- [leetcode] Regular Expression Matching
- LeetCode-Regular Expression Matching
- LeetCode——Regular Expression Matching
- leetcode 10 -- Regular Expression Matching
- LeetCode 10: Regular Expression Matching
- **LeetCode-Regular Expression Matching
- LeetCode Regular Expression Matching
- leetcode第一刷_Regular Expression Matching
- [Leetcode 10, Hard] Regular Expression Matching
- Leetcode_regular-expression-matching