72. 编辑距离

题目来源:

        LeetCode题目:72. 编辑距离 - 力扣(LeetCode)

解题思路:

       动态规划。对于长度未 m 和 n 的两个字符串 word1 和 word2,如果 word1[m-1]==word2[n-1],那么  dp[m-1][n-1]= min(dp[m-1][n-2]+1,dp[m-2][n-1]+1,dp[m-2,n-2]),否则 dp[m-1][n-1]= min(dp[m-1][n-2]+1,dp[m-2][n-1]+1,dp[m-2,n-2]+1)........可以通过倒推获得dp[m-1][n-1]。关于初始值的问题,显而易见的,当一个字符串为空串时,编辑距离为另一个字符串的长度。为了留出空串的空间,实际数组长度会比字符串长度大一。

解题代码:

class Solution:
    def minDistance(self, word1: str, word2: str) -> int:
        cnt=[[0]*(len(word1)+1) for each in range(len(word2)+1)]
        for i in range(len(word1)+1):
            cnt[0][i]=i
        for i in range(len(word2)+1):
            cnt[i][0]=i
        for i in range(1,len(word2)+1):
            for j in range(1,len(word1)+1):
                if word2[i-1]==word1[j-1]:
                    cnt[i][j]=min(min(cnt[i-1][j-1],cnt[i-1][j]+1),cnt[i][j-1]+1)
                else:
                    cnt[i][j]=min(min(cnt[i-1][j-1]+1,cnt[i-1][j]+1),cnt[i][j-1]+1)
        return cnt[len(word2)][len(word1)]
        

总结:

        我是真的没想到用动态规划来解题,看题解做的。


你可能感兴趣的:(#,二刷,LeetCode)