LC.P583[两个字符串的删除操作]

方法一:转化为最长公共子序列

求将两个字符串删除任意字符后能相同的最短步数,可以等价于求两个字符串的最长公共子序列LCS,最后使得两字符串删除任意字符后能相同的最短步数$= n - lcs + m - lcs$

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public int minDistance(String word1, String word2) {
int n = word1.length(), m = word2.length();
int[][] f = new int[n + 1][m + 1];
// 求最长公共子序列 (LC.P1143)
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
if (word1.charAt(i - 1) == word2.charAt(j - 1)) {
f[i][j] = f[i - 1][j - 1] + 1;
} else {
f[i][j] = Math.max(f[i][j - 1], f[i - 1][j]);
}
}
}
int lcs = f[n][m];
return n - lcs + m - lcs;
}
}
  • 时间复杂度:$O(n \times m)$
  • 空间复杂度:$O(n \times m)$

方法二:动态规划

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public int minDistance(String word1, String word2) {
int n = word1.length(), m = word2.length();
int[][] f = new int[n + 1][m + 1];
for (int i = 1; i <= n; ++i) f[i][0] = i;
for (int j = 1; j <= m; ++j) f[0][j] = j;
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
if (word1.charAt(i - 1) == word2.charAt(j - 1)) {
f[i][j] = f[i - 1][j - 1];
} else {
f[i][j] = Math.min(f[i - 1][j], f[i][j - 1]) + 1;
}
}
}
return f[n][m];
}
}
  • 时间复杂度:$O(n \times m)$
  • 空间复杂度:$O(n \times m)$