LeetCode刷题 Day56
583. Delete Operation for Two Strings
Given two strings word1 and word2, return the minimum number of steps required to make word1 and word2 the same.
In one step, you can delete exactly one character in either string.
Example 1:
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".
Example 2:
Input: word1 = "leetcode", word2 = "etco"
Output: 4
思路: 求出最长公共子序列的长度,然后用两个str长度之和 - 最长公共子序列*2
代码:
var minDistance = function(word1, word2) {
const [len1, len2] = [word1.length, word2.length];
let dp = Array(len1 + 1).fill(0).map(() => Array(len2 + 1).fill(0));
for (let i = 1; i <= len1; i++) {
for (let j = 1; j <= len2; j++) {
if (word1[i - 1] === word2[j - 1]) dp[i][j] = dp[i - 1][j - 1] + 1;
else dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
}
}
return len1 + len2 - dp[len1][len2] * 2;
};
时间复杂度: O(mn), 空间复杂度: O(mn)
72. Edit Distance
Given two strings word1 and word2, return the minimum number of operations required to convert word1 to word2.
You have the following three operations permitted on a word:
- Insert a character
- Delete a character
- Replace a character
Example 1:
Input: word1 = "horse", word2 = "ros"
Output: 3
Explanation:
horse -> rorse (replace 'h' with 'r')
rorse -> rose (remove 'r')
rose -> ros (remove 'e')
Example 2:
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 = 'ad' word2 = 'a', word1 删除d和 word2 添加d会达到一样的效果,而且dp结果也是相同的。
递推公式: 当word1[i - 1] === word2[j - 1], 这样就不用做任何操作 dp[i][j] = dp[i - 1][j - 1] 当 word1[i - 1] !== word2[j - 1], 可以做删除和替换操作, 替换: dp[i][j] = dp[i - 1][j - 1] + 1; 删除又可分为 删除word1: dp[i][j] = dp[i - 1][j] + 1; 删除word2: dp[i][j] = dp[i][j - 1] + 1;
初始化: dp[i][0] = i, dp[0][j] = j。dp[i][0] 可以理解为 word1[i]对比空字符串 word2需要做的操作, dp[0][j]同理。
代码:
var minDistance = function(word1, word2) {
const [len1, len2] = [word1.length, word2.length];
const dp = Array(len1 + 1).fill(0).map(() => Array(len2 + 1).fill(0));
for (let i = 0; i <= len1; i++) dp[i][0] = i;
for (let j = 0; j <= len2; j++) dp[0][j] = j;
for (let i = 1; i <= len1; i++) {
for (let j = 1; j <= len2; j++) {
if (word1[i - 1] === word2[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 - 1] + 1);
}
}
}
return dp[len1][len2];
}
时间复杂度: O(mn) 空间复杂度: O(mn)