LeetCode Regular Expression Matching
2015-11-12 07:58
232 查看
Description:
Implement regular expression matching with support for
Solution:
dp[i][j] represents whether s[0,i-1] and p[0,j-1] is a match.
We can have three situations s[i-1] and p[j-1]:
(1) Because we may have the situation that "" and ".*" is a match, so we need to start i from 0.
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
Solution:
dp[i][j] represents whether s[0,i-1] and p[0,j-1] is a match.
We can have three situations s[i-1] and p[j-1]:
if p[j] != '.' and [j] != '*' dp[i][j] = dp[i-1][j-1] + s[i-1] == p[j-1]; else if p[j] == '.' dp[i][j] = dp[i-1][j-1]; else // p[j] = '*' if (j>1) if (dp[i][j-1] || dp[i][j-2]) dp[i][j] = true else if(i>0 && dp[i-1][j] && (p[j-2]=='.' || s[i-1]==p[j-2] ) ) //(1) dp[i][j] = true
(1) Because we may have the situation that "" and ".*" is a match, so we need to start i from 0.
<span style="font-size:18px;">public class Solution { public boolean isMatch(String s, String p) { if (s == null || p == null) return false; int n = s.length(); int m = p.length(); boolean dp[][] = new boolean[n + 1][m + 1]; dp[0][0] = true; char ch1, ch2; for (int i = 0; i <= n; i++) { for (int j = 1; j <= m; j++) { ch2 = p.charAt(j - 1); if (ch2 == '*') { if (j > 1) { if (dp[i][j - 1] || dp[i][j - 2]) dp[i][j] = true; else if (i > 0 && (p.charAt(j - 2) == s.charAt(i - 1) || p .charAt(j - 2) == '.') && dp[i - 1][j]) dp[i][j] = true; } } else if (i > 0) { ch1 = s.charAt(i - 1); if (ch2 == '.') { dp[i][j] = dp[i - 1][j - 1]; } else { if (ch1 == ch2) dp[i][j] = dp[i - 1][j - 1]; } } } } return dp [m]; } }</span>
相关文章推荐
- c++头文件
- 欢迎使用CSDN-markdown编辑器
- 《串的基本操作》
- 网页字体助手 WebFont Helper
- 常用排序算法稳定性、时间复杂度分析
- java快速排序实现
- ASP.NET MVC- 使用PageList.Mvc分页
- Binary Tree Upside Down
- Android 实战 - 个人App乐逗项目(查看网页链接封装,播放视频封装)
- 谁说淘宝客不赚钱?用此招,票子流量手到擒来!
- Xamarin.iOS学习一:Hello.iOS 入门学习
- Spark学习体会
- iOS开发之GCD使用总结
- 直接插入排序 :Java实现
- List<String>Sort
- 在Style中定义动画类型
- GET 与POST一句话理解!
- 冒泡排序:JAVA
- LeetCode Edit Distance
- ——黑马程序员——OC中NSNumber、NSValue、NSDate 的使用总结