kim的每日刷题.LC.72.编辑距离

class Solution(object):
    def minDistance(self, word1, word2):
        """
        :type word1: str
        :type word2: str
        :rtype: int
        """
        dp = [[0]*(len(word2)+1) for _ in range(len(word1)+1)]
        # 边界条件:当输入是一个空串和一个非空串时
        # 编辑距离为非空串的长度(插入i次或者删除i次)
        for i in range(len(word1)+1):
            dp[i][0] = i
        for j in range(len(word2)+1):
            dp[0][j] = j
        for i in range(1, len(word1)+1):
            for j in range(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] + 1,
                        dp[i-1][j-1] + 1,
                        dp[i][j-1] + 1
                    )
        return dp[len(word1)][len(word2)]

s = Solution()
minEdit = s.minDistance('intention', 'execution')
print(minEdit)

 

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页