代码随想录训练营Day56| 583. 两个字符串的删除操作 72. 编辑距离 编辑距离总结篇

目录

学习目标

学习内容

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

  72. 编辑距离 


学习目标

  •  583. 两个字符串的删除操作 
  •  72. 编辑距离 
  •  编辑距离总结篇  

学习内容

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

583. 两个字符串的删除操作 - 力扣(LeetCode)https://leetcode.cn/problems/delete-operation-for-two-strings/

class Solution:
    def minDistance(self, word1: str, word2: str) -> int:
        m = len(word1)
        n = 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][j-1],dp[i-1][j])
        #print(dp)
        return m+n-2*dp[-1][-1]

  72. 编辑距离 

72. 编辑距离 - 力扣(LeetCode)https://leetcode.cn/problems/edit-distance/

class Solution:
    def minDistance(self, word1: str, word2: str) -> int:
        n = len(word1)
        m = len(word2)

        @cache
        def dfs(i,j):
            if i<0:
                return j+1 # 全增加
            if j<0:
                return i+1 # 全删除
            if word1[i]==word2[j]:
                return dfs(i-1,j-1)
            return min(dfs(i-1,j),dfs(i,j-1),dfs(i-1,j-1))+1 # 枚举三种操作
        return dfs(n-1,m-1)
class Solution:
    def minDistance(self, word1: str, word2: str) -> int:
        n = len(word1)
        m = len(word2)
        
        f = [[0]*(m+1)for _ in range(n+1)]
        f[0]=list(range(m+1))
        for i in range(1,n+1):
            for j in range(m+1):
                if j==0:
                    f[i][j]=i
                    continue
                if word1[i-1]==word2[j-1]:f[i][j]=f[i-1][j-1]
                else:
                    f[i][j]=min(f[i-1][j],f[i][j-1],f[i-1][j-1])+1
        #print(f)
        return f[-1][-1]

problems/动态规划总结篇.md · programmercarl/leetcode-master(代码随想录出品) - Gitee.comicon-default.png?t=N4P3https://gitee.com/programmercarl/leetcode-master/blob/master/problems/%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92%E6%80%BB%E7%BB%93%E7%AF%87.md

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