代码随想录算法训练营第五十六天| 第九章 动态规划:583.两个字符串的删除操作,72.编辑距离,编辑距离总结篇(python)

目录

583.两个字符串的删除操作

72.编辑距离

编辑距离总结篇


583.两个字符串的删除操作

视频讲解链接    文字讲解链接

方法一:直接以最小步数作为状态来计算

class Solution:
    def minDistance(self, word1: str, word2: str) -> int:
        m, n = len(word1), len(word2)
        #dp[i][j] 使得以i-1为尾的word1和以j-1为尾的word2相同所需的最小步数
        dp = [[0]*(n+1) for _ in range(m+1)] 
        for i in range(m+1):
            dp[i][0] = i
        for j in range(n+1):
            dp[0][j] = j
        
        for i in range(1, m+1):
            for j in range(1, n+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][j-1]+1, dp[i-1][j-1]+2)
        return dp[-1][-1]

方法二:计算最大公共子序列,之后长度相减得到答案

class Solution:
    def minDistance(self, word1: str, word2: str) -> int:
        m, n = len(word1), len(word2)
        dp = [[0]* (n+1) for _ in range(m+1)]
        for i in range(1, m+1):
            for j in range(1, n+1):
                if word1[i-1] == word2[j-1]:
                    dp[i][j] = dp[i-1][j-1]+1
                else:
                    dp[i][j] = max(dp[i-1][j], dp[i][j-1])
        return m + n - 2* dp[-1][-1]

72.编辑距离

视频讲解链接    文字讲解链接

class Solution:
    def minDistance(self, word1: str, word2: str) -> int:
        m,n = len(word1), len(word2)
        dp = [[0]* (n+1) for _ in range(m+1)]
        for i in range(m+1):
            dp[i][0] = i
        for j in range(n+1):
            dp[0][j] = j

        for i in range(1, m+1):
            for j in range(1, n+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][j-1]+1, dp[i-1][j-1]+1)
                    
        return dp[-1][-1]

编辑距离总结篇

文字讲解链接

你可能感兴趣的:(动态规划,算法,python,leetcode)