当前位置:网站首页>[Hot100]10. 正则表达式匹配
[Hot100]10. 正则表达式匹配
2022-06-30 06:47:00 【王六六的IT日常】
10. 正则表达式匹配
困难题
动态规划:
dp[i][j] 表示 s 的前 i 个是否能被 p 的前 j 个匹配
● 转移方程: 需要注意,由于 dp[0][0] 代表的是空字符的状态, 因此 dp[i][j] 对应的添加字符是 s[i - 1] 和 p[j - 1] 。
○ 当 p[j - 1] = ‘*’ 时, dp[i][j] 在当以下任一情况为 true时等于true :
■ dp[i][j-2]
● 将字符组合 p[j - 2] * 看作出现 0 次时,能否匹配;
■ dp[i-1][j]
● 且 p[j - 2] = s[i - 1]: 即让字符 p[j - 2]多出现 1 次时,能否匹配;
● 且 p[j - 2] = ‘.’:即让字符 ‘.’ 多出现 1 次时,能否匹配;
○ 当 p[j - 1] != ‘*’ 时, dp[i][j] 在当以下任一情况为true 时等于 true :
■ dp[i - 1][j - 1]
● 且 s[i - 1] = p[j - 1]: 即让字符 p[j - 1] 多出现一次时,能否匹配;
● 且 p[j - 1] = ‘.’: 即将字符 . 看作字符 s[i - 1] 时,能否匹配;
class Solution {
public boolean isMatch(String s, String p) {
int m = s.length() + 1, n = p.length() + 1;
boolean[][] dp = new boolean[m][n];
dp[0][0] = true;
// 初始化首行
for(int j = 2; j < n; j += 2)
dp[0][j] = dp[0][j - 2] && p.charAt(j - 1) == '*';
// 状态转移
for(int i = 1; i < m; i++) {
for(int j = 1; j < n; j++) {
if(p.charAt(j - 1) == '*') {
if(dp[i][j - 2]) dp[i][j] = true;
// 1.
else if(dp[i - 1][j] && s.charAt(i - 1) == p.charAt(j - 2)) dp[i][j] = true; // 2.
else if(dp[i - 1][j] && p.charAt(j - 2) == '.') dp[i][j] = true; // 3.
} else {
if(dp[i - 1][j - 1] && s.charAt(i - 1) == p.charAt(j - 1)) dp[i][j] = true; // 1.
else if(dp[i - 1][j - 1] && p.charAt(j - 1) == '.') dp[i][j] = true; // 2.
}
}
}
return dp[m - 1][n - 1];
}
}
class Solution {
public boolean isMatch(String s, String p) {
int m = s.length();
int n = p.length();
boolean[][] f = new boolean[m + 1][n + 1];
f[0][0] = true;
for (int i = 0; i <= m; ++i) {
for (int j = 1; j <= n; ++j) {
if (p.charAt(j - 1) == '*') {
f[i][j] = f[i][j - 2];
if (matches(s, p, i, j - 1)) {
f[i][j] = f[i][j] || f[i - 1][j];
}
} else {
if (matches(s, p, i, j)) {
f[i][j] = f[i - 1][j - 1];
}
}
}
}
return f[m][n];
}
public boolean matches(String s, String p, int i, int j) {
if (i == 0) {
return false;
}
if (p.charAt(j - 1) == '.') {
return true;
}
return s.charAt(i - 1) == p.charAt(j - 1);
}
}
边栏推荐
猜你喜欢
随机推荐
Go installation and configuration (1)
Pycharm shortcut key
ROS service communication programming
C language: exercise 3
Hao looking for a job
ftplib+ tqdm 上传下载进度条
RT thread application
No module named 'pyqt5 QtMultimedia‘
SOC_ AHB_ SD_ IF
RT thread Kernel Implementation (III): implementation of idle threads and blocking delay
Ffmplay is not generated during the compilation and installation of ffmpeg source code
Set in set (III)
Deep learning --- the weight of the three good students' scores (3)
Loading class `com. mysql. jdbc. Driver‘. This is deprecated. The new driver class is `com. mysql. cj. jdb
Four tips in numpy
记录一次腾讯测试开发工程师自动化接口测试实践经验
Arrangement of in-depth learning materials
ROS-URDF
Control method of UAV formation
IO stream (file class introduction)





![[my creation anniversary] one year anniversary essay](/img/98/f9305894747687465f86354fe08500.png)



