代码随想录算法训练营第五十六天

代码随想录算法训练营第五十六天| 583. 两个字符串的删除操作,72. 编辑距离

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

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

题目链接:两个字符串的删除操作

i/j e t c o
0 1 2 3 4
l 1 2 3 4 5
e 2 1 2 3 4
e 3 2 3 4 5
t 4 3 2 3 4
c 5 4 3 2 4
o 6 5 4 3 2
d 7 6 5 4 3
e 8 7 6 5 4

初始化是全删要的次数,然后递推公式是如果当前字母一样就等于左上角,不一样就等于左边和上面的最小值加1.

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

        for j in range(1,len(word2)+1):
            for i in range(1,len(word1)+1):
                if word2[j-1] == word1[i-1]:
                    dp[i][j] = dp[i-1][j-1]
                else:
                    dp[i][j] = min(dp[i-1][j],dp[i][j-1])+1
        return dp[-1][-1]

72. 编辑距离

题目链接:编辑距离

i/j r o s
0 1 2 3
h 1 1 2 3
o 2 2 1 2
r 3 2 2 2
s 4 3 3 2
e 5 4 4 3

以后画例子还是找个简单的太难的自己都算不清楚。

word1删除一个元素: dp[i][j] = dp[i - 1][j] + 1
word2删除一个元素(相当于word1增加一个元素):dp[i][j] = dp[i][j - 1] + 1
替换一个元素:dp[i][j] = dp[i -1][j - 1] + 1

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

        for j in range(1,len(word2)+1):
            for i in range(1,len(word1)+1):
                if word2[j-1] == word1[i-1]:
                    dp[i][j] = dp[i-1][j-1]
                else:
                    dp[i][j] = min(dp[i-1][j],dp[i][j-1],dp[i-1][j-1])+1
        return dp[-1][-1]

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