分析
-
本题的考点:动态规划。
-
用
a
表示word1
,用b
表示word2
,分析如下:
代码
- C++
class Solution {
public:
int minDistance(string a, string b) {
int n = a.size(), m = b.size();
a = ' ' + a, b = ' ' + b;
vector<vector<int>> f(n + 1, vector<int>(m + 1));
// 初始化
for (int j = 0; j <= m; j++) f[0][j] = j; // 将空字符串变为b[1~j]需要j步添加操作
for (int i = 0; i <= n; i++) f[i][0] = i; // 将a[1~i]变为空字符串需要i步删除操作
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++) {
f[i][j] = min(f[i - 1][j] + 1, f[i][j - 1] + 1);
if (a[i] == b[j]) f[i][j] = min(f[i][j], f[i - 1][j - 1]);
else f[i][j] = min(f[i][j], f[i - 1][j - 1] + 1);
}
return f[n][m];
}
};
- Java
class Solution {
public int minDistance(String word1, String word2) {
int n = word1.length(), m = word2.length();
char[] a = (" " + word1).toCharArray(), b = (" " + word2).toCharArray();
int[][] f = new int[n + 1][m + 1];
for (int i = 0; i <= m; i++) f[0][i] = i;
for (int i = 0; i <= n; i++) f[i][0] = i;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++) {
f[i][j] = Math.min(f[i - 1][j], f[i][j - 1]) + 1;
if (a[i] == b[j]) f[i][j] = Math.min(f[i][j], f[i - 1][j - 1]);
else f[i][j] = Math.min(f[i][j], f[i - 1][j - 1] + 1);
}
return f[n][m];
}
}
时空复杂度分析
-
时间复杂度:$O(n \times m)$,
n、m
为两个字符串的长度。 -
空间复杂度:$O(n \times m)$。