class Solution:
def minDistance(self, word1: str, word2: str) -> int:
# dp: 以i - 1结尾的word1和以j - 1结尾的word2相同需要的最小步数
# if word1[i - 1] == word2[j - 1]: dp[i][j] = dp[i - 1][j - 1]
# else: dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + 1
dp = [[0] * (len(word2) + 1) for _ in range(len(word1) + 1)]
for j in range(len(word2) + 1):
dp[0][j] = j
for i in range(len(word1) + 1):
dp[i][0] = i
for i in range(1, len(word1) + 1):
for j in range(1, len(word2) + 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], dp[i][j - 1]) + 1
return dp[-1][-1]
画一个二维数组图 递推一下就很清楚了
dp数组表示以i - 1结尾的word1和j - 1结尾的word2相同需要的最小步数,
dp[0][0]表示word1和word2都是空的情况,所以初始化的时候dp[0][j]就要等于j,意思是把word2变成空需要的步数,同理dp[i][0]要等于i,表示把word1变成空需要的步数。
递推公式分成两部分,如果是遍历到两个字符相等了,那么就直接dp[i][j] = dp[i - 1][j - 1] 因为以i - 2结尾的word1和j - 2结尾的word2相同需要的步数和以i - 1的相等
如果不相等,那就说明要多一步,要么在dp[i][j - 1]上多一步或者dp[i - 1][j]上多一步,因为求最小的,所以取个min。
class Solution:
def minDistance(self, word1: str, word2: str) -> int:
# dp: 以i - 1结尾的word1和以j - 1结尾的word2相同需要的最小步数
# if word1[i - 1] == word2[j - 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
dp = [[0] * (len(word2) + 1) for _ in range(len(word1) + 1)]
for j in range(len(word2) + 1):
dp[0][j] = j
for i in range(len(word1) + 1):
dp[i][0] = i
for i in range(1, len(word1) + 1):
for j in range(1, len(word2) + 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], dp[i][j - 1], dp[i - 1][j - 1]) + 1
return dp[-1][-1]
删除或者替换的情况都考虑,就是多一个dp[i - 1][j - 1]的情况