此题是Longest Common Subsequence变体
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
class Solution:
def minDistance(self, word1: str, word2: str) -> int:
m, n = len(word1), len(word2)
def longestCommonSubsequence(text1: str, text2: str) -> int:
m, n = len(text1), len(text2)
# dp[i][j] 表示 text1[..i] 和 text2[..j] 的最长公共子序列的长度
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m):
for j in range(n):
if text1[i] == text2[j]:
# 如果 text1[i] == text2[j] ,则必定选择这两个字符作为最长公共子序列的结尾,
# 那么状态 dp[i + 1][j + 1] 可由 dp[i][j] + 1 转移而来
dp[i + 1][j + 1] = dp[i][j] + 1
else:
# 如果 text1[i] != text2[j] ,
# 则 dp[i + 1][j + 1] 只能从 dp[i + 1][j] 和 dp[i][j + 1] 直接转移
dp[i + 1][j + 1] = max(dp[i + 1][j], dp[i][j + 1])
# dp[m][n] 就是 text1 和 text2 的最长公共子序列的长度
return dp[m][n]
return m + n - 2*longestCommonSubsequence(word1,word2)