- dp[i][j]表示字符串s[0...i]与字符串p[0...j]是否匹配。空字符串与空字符串是匹配的,dp[0][0] = true。
- s[i]与p[j]相等或通过'.'匹配, 那么s[0...i]和p[0...j] 是否匹配取决于s[0...i-1]与p[0...j-1]是否匹配。即dp[i][j] |= dp[i-1][j-1]。
- 用s[j]为'*',则
- 若用*匹配零次前一个字符,那么s[0...i]和p[0...j]是否匹配取决于s[0...i]和s[0...j-2]是否匹配, dp[i][j] |= dp[i][j-2];
- 若s[i]与p[j-1]匹配,则可用*匹配一次前面的字符,dp[i][j] |= dp[i-1][j]
class Solution {
public:
bool isMatch(string s, string p) {
int sSize = s.size();
int pSize = p.size();
vector<vector<int>> dp(sSize+1, vector<int>(pSize+1));
auto match = [&](int i, int j){
return i > 0 && (s[i-1] == p[j-1] || p[j-1] == '.');
};
dp[0][0] = true;
for(int i = 0; i < sSize + 1; i++){
for(int j = 1; j < pSize + 1; j++){
if(match(i, j)){
dp[i][j] |= dp[i-1][j-1];
}
if(p[j-1] == '*'){
dp[i][j] |= dp[i][j-2];
if(match(i, j-1)) dp[i][j] |= dp[i-1][j];
}
}
}
return dp[sSize][pSize];
}
};
- dp[i][j]表示字符串s[0...i]与字符串p[0...j]是否匹配。空字符串与空字符串是匹配的,dp[0][0] = true。
- 空字符串s与p匹配的一种情况是,p[0...j]每一个字符都是*,此时dp[0][j] |= dp[0][j-1]。
- s[i]与p[j]相等或通过'.'匹配, 那么s[0...i]和p[0...j] 是否匹配取决于s[0...i-1]与p[0...j-1]是否匹配。即dp[i][j] |= dp[i-1][j-1]。
- 若s[j]为*, 可:
- 匹配空字符串,dp[i][j] |= dp[i][j-1];
- 匹配任意一个字符,dp[i][j] |= dp[i-1][j];
class Solution {
public:
bool isMatch(string s, string p) {
int sSize = s.size();
int pSize = p.size();
vector<vector<int>> dp(sSize+1, vector<int>(pSize+1));
dp[0][0] = 1;
for(int j = 1; j < pSize + 1; j++){
if(p[j-1] == '*'){
dp[0][j] |= dp[0][j-1];
}
}
for(int i = 1; i < sSize+1; i++){
for(int j = 1; j < pSize+1; j++){
if(s[i-1] == p[j-1] || p[j-1] == '?') dp[i][j] |= dp[i-1][j-1];
if(p[j-1] == '*'){
dp[i][j] |= dp[i-1][j];
dp[i][j] |= dp[i][j-1];
}
}
}
return dp[sSize][pSize];
}
};