9.【动态规划】编辑距离

2019-11-11  本文已影响0人  blackzero2193

题目链接:https://leetcode-cn.com/problems/edit-distance/
描述:给定两个单词 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')
# 递归的方法,但是时间复杂度较高,需要使用一个dp数组记录重复操作的步骤
    def minDistance(word1, word2):
        """
        :type word1: str
        :type word2: str
        :rtype: int
        """
        if word1 == '':
            return len(word2)
        if word2 == '':
            return len(word1)

        if word1[-1] == word2[-1]:
            return self.minDistance2(word1[:-1], word2[:-1])
        else:
            res = 1 + min(
                self.minDistance2(word1[:-1], word2[:-1]),
                self.minDistance2(word1, word2[:-1]),
                self.minDistance2(word1[:-1], word2)
            )
        return res
class Solution(object):
    def minDistance(self, word1, word2):
        """
        :type word1: str
        :type word2: str
        :rtype: int
        """
        n = len(word1)
        m = len(word2)
        dp = [[0 for j in range(m+1)] for i in range(n+1)]
        for i in range(n+1):
            for j in range(m+1):
                if i == 0:
                    dp[i][j] = j
                    continue
                if j == 0:
                    dp[i][j] = i
                    continue
                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],
                                   dp[i][j - 1]) + 1
        return dp[n][m]
上一篇下一篇

猜你喜欢

热点阅读