LeetCode Edit Distance

LeetCode解题之Edit Distance

原题

求两个字符串之间的最短编辑距离,即原来的字符串至少要经过多少次操作才能够变成目标字符串,操作包括删除一个字符、插入一个字符、更新一个字符。

注意点:

例子:

输入: word1 = “heo”, word2 = “hello”

输出: 2

解题思路

又是一道典型的动态规划。现在用dp[i][j]来表示字符串word1[:i]转化到word2[:j]的最小编辑距离,那么最后一次操作可能有三种情况:

  • 在word1[:i-1]转化为word2[:j]的基础上再删除word1[i]
  • 在word1[:i]转化为word2[:j-1]的基础上再插入word2[j]
  • 在word1[:i-1]转化为word2[:j-1]的基础上将word1[i]更新为word2[j](可能本来就相同)

所以有如下递推式:dp[i][j] = min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + onemore)

AC源码

class Solution(object):
    def minDistance(self, word1, word2):
        """ :type word1: str :type word2: str :rtype: int """
        m = len(word1)
        n = len(word2)
        dp = [[0 for __ in range(m + 1)] for __ in range(n + 1)]
        for j in range(m + 1):
            dp[0][j] = j
        for i in range(n + 1):
            dp[i][0] = i
        for i in range(1, n + 1):
            for j in range(1, m + 1):
                onemore = 1 if word1[j - 1] != word2[i - 1] else 0
                dp[i][j] = min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + onemore)
        return dp[n][m]


if __name__ == "__main__":
    assert Solution().minDistance("", "a") == 1
    assert Solution().minDistance("faf", "efef") == 2

欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源码。

你可能感兴趣的:(LeetCode,算法,python,动态规划,编辑距离)