LeetCode Regular Expression Matching
来源:互联网 发布:unity3d 路径动画 编辑:程序博客网 时间:2024/05/20 20:05
Description:
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
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[n][m];}}</span>
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
- 希尔排序:Java(最小增量排序)
- Spark学习体会
- java快速排序实现
- Android 实战 - 个人App乐逗项目(查看网页链接封装,播放视频封装)
- Binary Tree Upside Down
- LeetCode Regular Expression Matching
- 常用排序算法稳定性、时间复杂度分析
- 乐视推相亲节目,“十周嫁出去”为何深得网友支持?
- 显示Intent和隐式Intent的区别
- 欢迎使用CSDN-markdown编辑器
- c++头文件
- Java学习笔记(八)异常及图形界面
- 我们的智慧型生活离我们还有多远
- java集合之EnumSet