Thinking process
dp[i][j] is the whether p [0 ... i] matches s [0 ... j]
- dp[i - 1][j - 1], if the character at p[i] is '?'
- dp[i][j - 1] or dp[i - 1][j - 1] or dp[i - 1][j], if the character at p[i] is *
- true, if character at s[j] == character at p[i] and dp[i - 1][j - 1] equals to true
Mistakes
the index range should include length s and length p
public class Solution {
public boolean isMatch(String s, String p) {
int lenS = s.length();
int lenP = p.length();
boolean[][] dp = new boolean[lenP + 1][lenS + 1];
//init
dp[0][0] = true;
for (int i = 1; i <= lenP; ++i) {
if (p.charAt(i - 1) == '*') {
dp[i][0] = dp[i - 1][0];
}
}
//iterate over s and p
for (int i = 1; i <= lenP; ++i) {
for (int j = 1; j <= lenS; ++j) {
if (p.charAt(i - 1) == '?') {
dp[i][j] = dp[i - 1][j - 1];
} else if (p.charAt(i - 1) == '*') {
if (dp[i - 1][j] || dp[i - 1][j - 1] || dp[i][j - 1]) {
dp[i][j] = true;
}
} else {
if (s.charAt(j - 1) == p.charAt(i - 1) && dp[i - 1][j - 1]) {
dp[i][j] = true;
}
}
}
}
return dp[lenP][lenS];
}
}