算法72. 编辑距离
题目
给你两个单词 word1 和 word2, 请返回将 word1 转换成 word2 所使用的最少操作数 。
你可以对一个单词进行如下三种操作:
- 插入一个字符
- 删除一个字符
- 替换一个字符
示例 1:
输入:word1 = “horse”, word2 = “ros”
输出:3
解释:
horse -> rorse (将 ‘h’ 替换为 ‘r’)
rorse -> rose (删除 ‘r’)
rose -> ros (删除 ‘e’)
示例 2:
输入:word1 = “intention”, word2 = “execution”
输出:5
解释:
intention -> inention (删除 ‘t’)
inention -> enention (将 ‘i’ 替换为 ‘e’)
enention -> exention (将 ‘n’ 替换为 ‘x’)
exention -> exection (将 ‘n’ 替换为 ‘c’)
exection -> execution (插入 ‘u’)
提示:
- 0 <= word1.length, word2.length <= 500
- word1 和 word2 由小写英文字母组成
题解
class Solution:def minDistance(self, word1: str, word2: str) -> int:n, m = len(word1), len(word2)c = {}def dfs(i:int,j:int)->int:if (i,j) in c:return c[(i,j)]if i<0:# 执行插入动作j+1次c[(i,j)]=j+1return j+1if j<0:# 执行删除动作i+1次c[(i,j)]=i+1return i+1if word1[i] == word2[j]:count_1=dfs(i-1,j-1)c[(i,j)]=count_1return count_1# 需要理解dfs(i-1,j)可以表示删除动作,因为word1变成word2需要word1去掉一个字符变成下一步的子问题,那么一定是执行的是word1删除掉一个字符。# dfs(i,j-1)表示插入,因为word1变成word2需要word2去掉一个字符变成下一步的子问题,那么一定是word1插入一个字符之后,word2去掉一个字符变成子问题。# dfs(i-1,j-1)表示替换,最后一个字符替换成一样的了,那么下一个子问题就可以都去掉一个字符做下一步比较了 count_2=min(dfs(i-1,j),dfs(i,j-1),dfs(i-1,j-1))+1c[(i,j)]=count_2return count_2return dfs(n-1,m-1)