【leetcode】72. Edit Distance
题目如下:
解题思路:这题和【leetcode】583. Delete Operation for Two Strings也是相似的,只不过多了一种替换的操作。具体的解析可以参考《编程之美》中的《寻找相似字符串》章节,有详细的解释。不过书中给的解法是递归,在本题会TEL,所以需要改成动态规划。如果如果word1[i] != word2[j],递推表达式变成:dp[i][j] = min(dp[i-1][j],dp[i][j-1],dp[i-1][j-1])+1。
代码如下:
class Solution(object): def minDistance(self, word1, word2): """ :type word1: str :type word2: str :rtype: int """ if len(word1) == 0 or len(word2) == 0: return abs(len(word2) - len(word1)) dp = [[0 for x in range(len(word2)+1)] for x in range(len(word1)+1)] for i in xrange(1,len(word1)+1): dp[i][0] = i for j in xrange(1,len(word2)+1): dp[0][j] = j for i in xrange(1,len(word1)+1): for j in xrange(1,len(word2)+1): if word1[i-1] == word2[j-1]: dp[i][j] = dp[i-1][j-1] else: dp[i][j] = min(dp[i-1][j],dp[i][j-1],dp[i-1][j-1])+1 return dp[-1][-1]