583. 两个字符串的删除操作
我的方法,先求出两者的最长公共子序列长度,再用两个字符串的长度相减就是两者分别要做操作的步数:
class Solution {public int minDistance(String word1, String word2) {int[][] dp = new int[word1.length() + 1][word2.length() + 1];for (int i = 1; i <= word1.length(); i++) {for (int j = 1; j<= word2.length(); j++) {if (word1.charAt(i - 1) == word2.charAt(j - 1)) {dp[i][j] = dp[i - 1][j - 1] + 1;}else{dp[i][j] = Math.max(dp[i][j - 1], dp[i - 1][j]);}}}return word1.length() - dp[word1.length()][word2.length()] + word2.length() - dp[word1.length()][word2.length()];}
}
涉及的操作太多了,没啥思路,直接看题解。
- 确定dp数组含义
dp[i][j] 表示以下标i-1为结尾的字符串word1,和以下标j-1为结尾的字符串word2,最近编辑距离为dp[i][j]。
- 确定递推公式
主要还是考虑word1[i - 1]和word2[j - 1]的相等情况
if (word1[i - 1] == word2[j - 1])不操作
if (word1[i - 1] != word2[j - 1])增删换
-
相等:dp[i][j] = dp[i - 1][j - 1];
-
不相等:
- 删除word1中的:dp[i][j] = dp[i - 1][j] + 1;
- 删除word2中的:dp[i][j] = dp[i][j - 1] + 1;
(这里没有添加,因为一个添加就相当于另一个删除)
- 替换:
word1
替换word1[i - 1],
使其与word2[j - 1]
相同,此时不用增删加元素:dp[i][j] = dp[i - 1][j - 1] + 1;
- 确定dp数组初始化
dp[i][0]:words1[i - 1]和words2[-1](空字符串),全部删除,等于i
dp[0][j] 同理为j
- 遍历顺序
从前往后,所以在dp矩阵中一定是从左到右从上到下去遍历。
- 举例推导DP数组
最终代码:
class Solution {public int minDistance(String word1, String word2) {int dp[][] = new int[word1.length() + 1][word2.length() + 1];for (int i = 0; i <= word1.length(); i++) {dp[i][0] = i;}for (int i = 0; i <= word1.length(); i++) {dp[i][0] = i;}for (int j = 0; j <= word2.length(); j++) {dp[0][j] = j;}for (int i = 1; i <= word1.length(); i++) {for (int j = 1; j <= word2.length(); j++) {if (word1.charAt(i - 1) == word2.charAt(j - 1)) {dp[i][j] = dp[i - 1][j - 1];} else {dp[i][j] = Math.min(dp[i - 1][j - 1] + 1, dp[i - 1][j] + 1);dp[i][j] = Math.min(dp[i][j], dp[i][j - 1] + 1);}}}return dp[word1.length()][word2.length()];}}