leetcode: Regular Expression Matching
来源:互联网 发布:做淘宝刷好评要交钱吗? 编辑:程序博客网 时间:2024/06/06 04:37
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") → falseisMatch("aa","aa") → trueisMatch("aaa","aa") → falseisMatch("aa", "a*") → trueisMatch("aa", ".*") → trueisMatch("ab", ".*") → trueisMatch("aab", "c*a*b") → true
对于S[i]和P[j]:
如果P[j+1]!='*',S[i] == P[j]=>匹配下一位(i+1, j+1),S[i]!=P[j]=>匹配失败;
如果P[j+1]=='*',S[i]==P[j]=>匹配下一位(i+1, j+2)或者(i, j+2),S[i]!=P[j]=>匹配下一位(i,j+2)。
匹配成功的条件为S[i]=='\0' && P[j]=='\0'。
class Solution {public: bool isMatch(string s, string p) { /*vector<vector<bool> > dp(s.size() + 1, vector<bool>(p.size() + 1, false)); dp[0][0] = true; for( int i = 1; i <= p.size(); ++i) dp[0][i] = '*' == p[i-1] && i > 1 && dp[0][i-2]; for( int i = 1; i <= s.size(); ++i){ for( int j = 1; j <= p.size(); ++j){ if(p[j-1] != '*') dp[i][j] = dp[i-1][j-1] && (s[i-1] == p[j-1] || p[j-1] == '.'); else dp[i][j] = dp[i-1][j] && j > 1 && (s[i-1] == p[j-2] || p[j-2] == '.') || dp[i][j-1] || j > 1 && dp[i][j-2]; } } return dp[s.size()][p.size()];*/ if(p == "*") return true; return core(s, p, 0, 0); } bool core(string s, string p, int i, int j){ if( j >= p.size()) return i >= s.size(); if( p[j+1] != '*'){ if(s[i] == p[j] || (p[j] == '.' && i < s.size())) return core(s, p, i+1, j+1); else return false; } else{ while(s[i] == p[j] || (p[j] == '.' && i < s.size())){ if( core(s, p, i, j + 2)) return true; ++i; } return core(s, p, i, j + 2); } }};
0 0
- LeetCode: Regular Expression Matching
- LeetCode: Regular Expression Matching
- leetcode Regular Expression Matching
- [Leetcode] Regular Expression Matching
- [LeetCode]Regular Expression Matching
- LeetCode-Regular Expression Matching
- Regular Expression Matching LeetCode
- 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
- leetcode: Regular Expression Matching
- LeetCode Regular Expression Matching
- Leetcode: Regular Expression Matching
- leetcode:Regular Expression Matching
- Action处理结果
- hdu 1850 nim游戏
- C/C++内存对齐
- A+B Problem III
- Python垃圾回收机制
- leetcode: Regular Expression Matching
- SSH三大框架之struts2
- 论文中的常见英文缩写
- Linked List part1 : node
- 【前端开发】25种提高网页加载速度的方法和技巧
- 21天学通Java学习笔记-Day08(数据结构)
- acdream 1127 Base Station 树状数组
- NYOJ 255 C小加 之 随机数
- WPF技术触屏上的应用系列(六): 视觉冲击、超炫系统主界面、系统入口效果实现