● 583. 两个字符串的删除操作
Given two strings word1 and word2, return the minimum number of steps required to make word1 and word2 the same. can delete in either string.
Input: word1 = “sea”, word2 = “eat”
Output: 2
Explanation: You need one step to make “sea” to “ea” and another step to make “eat” to “ea”.
这题可以同时在两个字符串进行删除操作,问最少的操作次数( Math.min )。
如果word1[i-1] = word2[j-1],那么就不用进行删除,只用看前面需要多少次删除。
如果不等,就表示需要删除,可以删除word1或者word2,如果同时删除word1[i-1] and word2[j-1],步数需要+2,但其实也包含在了dp[i-1][j]+1中,即可以在[0:j]中再删除word2[j-1]
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 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, dp[i][j-1]+1); // include dp[i-1][j-1]+2}}}return dp[word1.length()][word2.length()];}
}
● 72. 编辑距离
word1 -> word2
Insert a character
Delete a character
Replace a character
Input: word1 = “intention”, word2 = “execution”
Output: 5
Explanation:
intention -> inention (remove ‘t’)
inention -> enention (replace ‘i’ with ‘e’)
enention -> exention (replace ‘n’ with ‘x’)
exention -> exection (replace ‘n’ with ‘c’)
exection -> execution (insert ‘u’)
根据前面三题铺垫,就比较简单了。
word1[i-1] = word2[j-1],不用任何编辑,继续看word1[0: i-2]和word2[0: j-2]之间的操作数。
不相等,代表需要编辑操作:
- delete word1, word1删除一个元素,那么就是以下标i - 2为结尾的word1 与 j-1为结尾的word2的最近编辑距离 再加上一个操作。
- insert word1,也可以看做delete word2,比较的是word1[i]和word2[j-1],再加上一步操作。
- replace word1 with one, word1和word2都抛弃最后一位,再加上1。
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 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 {// delete, insert, replacedp[i][j] = Math.min(Math.min(dp[i-1][j], dp[i][j-1]), dp[i-1][j-1]) +1;}}}return dp[word1.length()][word2.length()];}
}