天若有情天亦老
人间正道是沧桑
44. Wildcard Matching
给出dfs+记忆搜索的。。。
class Solution {
public:
int match(const char *a, const char *b, const char *ab, const char *bb, vector<vector<int>> &dp) {
if (dp[a - ab][b - bb]) return dp[a - ab][b - bb];
if (*a == 0 && *b == 0) return dp[a - ab][b - bb] = 1;
if (*a == *b || (*b == '?' && *a))
return dp[a - ab][b - bb] = match(a + 1, b + 1, ab, bb, dp);
else if (*b == '*') {
if (*a) {
bool ans = (match(a + 1, b, ab, bb, dp) > 0) || (match(a + 1, b + 1, ab, bb, dp) > 0) || (match(a, b + 1, ab, bb, dp) > 0);
if (ans)
return dp[a - ab][b - bb] = 1;
else return dp[a - ab][b - bb] = -1;
}
else return dp[a - ab][b - bb] = match(a, b + 1, ab, bb, dp);
} else return dp[a - ab][b - bb] = -1;
}
bool isMatch(string s, string p) {
vector<vector<int>> dp(s.length() + 1, vector<int>(p.length() + 1, 0));
return match(s.data(), p.data(), s.data(), p.data(), dp) == 1;
}
};
然后可简化成dp。。。但是dp不如上面的块。。。
class Solution {
public:
bool isMatch(string s, string p) {
vector<vector<bool>> dp(s.length() + 1, vector<bool>(p.length() + 1, false));
dp[0][0] = true;
for (int j = 1; j <= p.length(); j++) {
if (p[j - 1] == '*') dp[0][j] = true;
else break;
}
for (int i = 1; i <= s.length(); i++) {
for (int j = 1; j <= p.length(); j++) {
if (p[j - 1] == '*')
dp[i][j] = dp[i][j - 1] || dp[i - 1][j] || dp[i - 1][j - 1];
else if (s[i - 1] == p[j - 1] || p[j - 1] == '?')
dp[i][j] = dp[i - 1][j - 1];
else dp[i][j] = false;
}
}
return dp[s.length()][p.length()];
}
};
72. Edit Distance
dp[i][j]
表示word1前i个字母最少可以经过dp[i][j]
次操作变成word2的前j个字母。
class Solution {
public:
int minDistance(string word1, string word2) {
int m = word1.length(), n = word2.length();
vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));
for (int i = 0; i <= m; i++) dp[i][0] = i;
for (int j = 0; j <= n; j++) dp[0][j] = j;
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (word1[i-1] == word2[j-1]) {
int minitem = min(dp[i-1][j-1], dp[i-1][j] + 1);
dp[i][j] = min(minitem, dp[i][j-1] + 1);
} else {
dp[i][j] = 1 + min(dp[i][j-1], min(dp[i-1][j], dp[i-1][j-1]));
}
}
}
return dp[m][n];
}
};