[LeetCode]10. Regular Expression Matching
来源:互联网 发布:中国基尼系数 知乎 编辑:程序博客网 时间:2024/06/15 20:49
https://leetcode.com/problems/regular-expression-matching/
给的case:ab -- .* --> true 是因为*代表前一位重复零次或多次,前一位是. 所以可以转化成..
DP问题,状态转移方程如下:
1, If p.charAt(j) == s.charAt(i) : dp[i][j] = dp[i-1][j-1];
2, If p.charAt(j) == '.' : dp[i][j] = dp[i-1][j-1];
3, If p.charAt(j) == '*':
here are two sub conditions:
1 if p.charAt(j-1) != s.charAt(i) : dp[i][j] = dp[i][j-2] //in this case, a* only counts as empty
2 if p.charAt(i-1) == s.charAt(i) or p.charAt(i-1) == '.':
dp[i][j] = dp[i-1][j] //in this case, a* counts as multiple a
or dp[i][j] = dp[i][j-1] // in this case, a* counts as single a
or dp[i][j] = dp[i][j-2] // in this case, a* counts as empty
初始化DP数组时是s为空,如果当前p位置i为*,同时i - 2为true,此时可以使得*代表零个前一位置数,从而当前位置为true
public class Solution { public boolean isMatch(String s, String p) { boolean[][] dp = new boolean[s.length() + 1][p.length() + 1]; dp[0][0] = true; for (int i = 0; i < p.length(); i++) { if (p.charAt(i) == '*' && dp[0][i - 1]) { dp[0][i + 1] = true; } } for (int i = 0; i < s.length(); i++) { for (int j = 0; j < p.length(); j++) { if (p.charAt(j) == '.') { dp[i + 1][j + 1] = dp[i][j]; } if (p.charAt(j) == s.charAt(i)) { dp[i + 1][j + 1] = dp[i][j]; } if (p.charAt(j) == '*') { if (p.charAt(j - 1) != s.charAt(i)) { dp[i + 1][j + 1] = dp[i + 1][j - 1]; } if (p.charAt(j - 1) == s.charAt(i) | p.charAt(j - 1) == '.') { dp[i + 1][j + 1] = (dp[i + 1][j] || dp[i + 1][j - 1] || dp[i][j + 1]); } } } } return dp[s.length()][p.length()]; }}
- [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
- 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
- LeetCode 10. Regular Expression Matching
- leetcode 10. Regular Expression Matching
- Leetcode-10. Regular Expression Matching
- 【leetcode】10. Regular Expression Matching
- Impala与Hive的比较
- 每天一个linux命令——more
- JPA @PreUpdate等更新其他实体
- 解决依赖库中BuildConfig.DEBUG的值总为False的问题
- 80老翁然人生(336):宣传贯彻《网络安全法》,必须批判网络违纪派
- [LeetCode]10. Regular Expression Matching
- MFC程序逆向 – 消息篇(上)+(下)
- js中数组的4种遍历方式
- Java核心类库——IO原理和用法
- javascript DOM操作
- SQLServer中的视图介绍
- Java实现1+2+...+n,不用乘除符号,不用if等条件判断,不用for等循环
- 软件概要设计与详细设计的区别
- 音视频编码格式汇总