583. Delete Operation for Two Strings
Problem
Return the minimum number of characters you must delete in total from word1 and word2 to make them equal.
Example: word1 = "sea", word2 = "eat" → 2
Characters kept = the LCS; everything else is deleted: m + n − 2·LCS.
Complexity: O(m·n).
class Solution:
def minDistance(self, word1: str, word2: str) -> int:
n = len(word2)
dp = [0] * (n + 1)
for a in word1:
diag = 0
for j in range(1, n + 1):
up = dp[j]
dp[j] = diag + 1 if a == word2[j - 1] else max(dp[j], dp[j - 1])
diag = up
return len(word1) + n - 2 * dp[n]
assert Solution().minDistance("sea", "eat") == 2
assert Solution().minDistance("leetcode", "etco") == 4
class Solution {
public int minDistance(String a, String b) {
int m = a.length(), n = b.length();
int[][] dp = new int[m + 1][n + 1];
for (int i = 1; i <= m; i++)
for (int j = 1; j <= n; j++)
dp[i][j] = a.charAt(i - 1) == b.charAt(j - 1) ? dp[i - 1][j - 1] + 1 : Math.max(dp[i - 1][j], dp[i][j - 1]);
return m + n - 2 * dp[m][n];
}
}
func minDistance(word1 string, word2 string) int {
n := len(word2)
dp := make([]int, n+1) // LCS row; everything outside the LCS gets deleted
for i := 0; i < len(word1); i++ {
diag := 0
for j := 1; j <= n; j++ {
up := dp[j]
if word1[i] == word2[j-1] {
dp[j] = diag + 1
} else {
dp[j] = max(dp[j], dp[j-1])
}
diag = up
}
}
return len(word1) + n - 2*dp[n]
}