[Leetcode]_10 Regular Expression Matching
2017-04-01 15:33
369 查看
注意:
ab <==> .* true
.* => .. => ab
ab <==> .* true
.* => .. => ab
1
p.empty() && s.empty() == true => true && s.empty() == false => false s: p: finally: a => a* => s, p.substr(2) or s.substr(1), p => .* => s, p.substr(2) or s.substr(1), p => a => s.substr(1), p.substr(1) => . => s.substr(1), p.substr(1) => else => false
class Solution { public: bool isMatch(string s, string p) { if( p.empty() ) return s.empty(); else if( p.length() > 1 && p[1] == '*' ) { if( (s[0] == p[0] or p[0] == '.') and !s.empty() ) return (isMatch(s, p.substr(2)) or isMatch(s.substr(1), p)); return isMatch(s, p.substr(2)); } else{ if( (s[0] == p[0] or p[0] == '.') and !s.empty() ) return isMatch(s.substr(1), p.substr(1)); } return false; } };
2.DP
matchArray[i][j]: matchArray[i-1][j-1] p[j-1] == '*' => matchArray[i][j] = matchArray[i][j-2] || (s[i-1] == p[j-2] || p[j-2] == '.') && matchArray[i-1][j]; else => matchArray[i][j] = matchArray[i-1][j-1] && (s[i-1] == p[j-1] || p[j-1] == '.'); class Solution { public: bool isMatch(string s, string p) { int sLen = s.length(), pLen = p.length(); bool matchArray[1001][1001]; matchArray[0][0] = true; for(int i = 1; i <= sLen; i++) matchArray[i][0] = false; for(int j = 1; j <= pLen; j++) matchArray[0][j] = j > 1 && p[j-1] == '*' && matchArray[0][j-2]; for(int i = 1; i <= sLen; i++) { for(int j = 1; j <= pLen; j++) { if( p[j-1] == '*' ) matchArray[i][j] = matchArray[i][j-2] || (s[i-1] == p[j-2] || p[j-2] == '.') && matchArray[i-1][j]; else matchArray[i][j] = matchArray[i-1][j-1] && (s[i-1] == p[j-1] || p[j-1] == '.'); } } return matchArray[sLen][pLen]; } };
相关文章推荐
- Leetcode 10: Regular Expression Matching
- 刷LeetCode(10)——Regular Expression Matching
- [LeetCode-Algorithms-10] "Regular Expression Matching" (2017.10.12-WEEK6)
- [leetcode] 10.Regular Expression Matching
- LeetCode 10 Regular Expression Matching
- leetcode-10 Regular Expression Matching
- leetcode 10 Regular Expression Matching
- LeetCode_OJ【10】Regular Expression Matching
- LeetCode题目: 10. Regular Expression Matching
- LeetCode----10**. Regular Expression Matching
- LeetCode 10: Regular Expression Matching
- [leetcode 10] Regular Expression Matching
- LeetCode (10): Regular Expression Matching [HARD]
- Leetcode(10)Regular Expression Matching
- LeetCode 10 - Regular Expression Matching
- LeetCode (10)Regular Expression Matching
- LeetCode 10 Regular Expression Matching
- leetcode 10 Regular Expression Matching(简单正则表达式匹配)
- LeetCode-10-Regular-Expression-Matching 递归模拟正则表达式
- [leetcode] 10 Regular Expression Matching