问题:
# 给你两个单词 word1 和 word2,请你计算出将 word1 转换成 word2 所使用的最少操作数 。
#
# 你可以对一个单词进行如下三种操作:
#
#
# 插入一个字符
# 删除一个字符
# 替换一个字符
#
#
#
#
# 示例 1:
#
#
# 输入:word1 = "horse", word2 = "ros"
# 输出:3
# 解释:
# horse -> rorse (将 ‘h‘ 替换为 ‘r‘)
# rorse -> rose (删除 ‘r‘)
# rose -> ros (删除 ‘e‘)
方法:最有子问题,动态规划
def editDistinct(w1, w2): l1 = len(w1) l2 = len(w2) if not w1 and not w2: return 0 if l1 * l2 == 0: return l1 + l2 # dp = [[0]*(l2+1) for _ in range(l1+1)] dp = [[i+j for i in range(l2+1)] for j in range(l1+1)] for i in range(l1+1): dp[i][0] = i for j in range(l2+1): dp[0][j] = j for i in range(1, l1+1): for j in range(1, l2+1): dp[i][j] = min(dp[i-1][j]+1, dp[i][j-1]+1, dp[i-1][j-1]+int(w1[i-1]!=w2[j-1])) return dp[l1][l2]
原文:https://www.cnblogs.com/demo-deng/p/14842575.html