Leetcode-Dynamically Programming-Edit Distance-hard

https://www.youtube.com/watch?v=MiqoA-yF-0M

Leetcode-Dynamically Programming-Edit Distance-hard_第1张图片

class Solution:
    def minDistance(self, word1: str, word2: str) -> int:
        if word1==word2:
            return 0
        dp=[]
        n=len(word1)
        m=len(word2)
        for i in range(m+1):
            dp.append([0]*(n+1))
            
        for j in range(1,n+1):
            dp[0][j]=j
        for i in range(1,m+1):
            dp[i][0]=i
        
        for i in range (1,m+1):
            for j in range(1,n+1):
                if word1[j-1]==word2[i-1]:
                    dp[i][j]=min(dp[i-1][j-1],1+dp[i-1][j],1+dp[i][j-1])#replace 选项不用操作,insert 和delete 仍然要操作
                else:
                    dp[i][j]=min(1+dp[i-1][j-1],1+dp[i-1][j],1+dp[i][j-1])
                    
        return dp[-1][-1]

 

你可能感兴趣的:(动态规划,Python,Leetcode)