https://leetcode-cn.com/problems/regular-expression-matching/solution/dong-tai-gui-hua-zen-yao-cong-0kai-shi-si-kao-da-b/
p[j]表示p第j个字母(p.charAt(j)),s[i]表示s的第i个字母
dp[i][j] 表示s的前i个字母与p的前j个字母是否匹配
- 如果 p[j] == s[i] : dp[i][j] = dp[i-1][j-1];
- 如果 p[j] == ‘.’ : dp[i][j] = dp[i-1][j-1];
- 如果 p[j] == ‘*’:
- 如果 p[j-1] != s[i] : dp[i][j] = dp[i][j-2] //in this case, a* only counts as empty
- 如果 p[j-1] == s[i] or p[j-2] == ‘.’:
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
public boolean isMatch(String s, String p) {
int m = s.length();
int n = p.length();
boolean[][] dp = new boolean[m+1][n+1];
dp[0][0] = true;//dp[i][j] 表示 s 的前 i 个是否能被 p 的前 j 个匹配
for (int i = 1; i <= n; i++) {
if (p.charAt(i-1) == '*' && dp[0][i-2]) {
dp[0][i] = true;
}
}
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (p.charAt(j-1) == '.' || p.charAt(j-1) == s.charAt(i-1)) {
dp[i][j] = dp[i-1][j-1];
}
else if (p.charAt(j-1) == '*') {
if (p.charAt(j-2) != s.charAt(i-1) && p.charAt(j-2) != '.') {
dp[i][j] = dp[i][j-2];
}
else {
dp[i][j] = dp[i-1][j] || dp[i][j-1] || dp[i][j-2];
// dp[i][j] = dp[i-1][j] 多个字符匹配的情况
// dp[i][j] = dp[i][j-1] 单个字符匹配的情况
// dp[i][j] = dp[i][j-2] 没有匹配
}
}
}
}
return dp[m][n];
}