题目地址
https://leetcode-cn.com/problems/edit-distance/
解题
动态规划
由于只能执行,替换,插入,删除操作
假设dp[i][j] 为word1[1:i]和word2[1:j]的编辑距离
那么dp[i-1][j-1] 为word1[1:i-1]和word2[1:j-1]的编辑距离
如何由dp[i-1][j-1] 到dp[i][j]
如果 i = j :
dp[i][j] = dp[i-1][j-1]
如果i != j:
那dp[i][j] 可以是 dp[i-1][j-1]经过一次操作,即:
dp[i][j] = dp[i-1][j-1] + 1
也可以是dp[i-i][j]经过一次操作,即:
dp[i][j] = dp[i-1][j] + 1
也可以是dp[i-i][j]经过一次操作,即:
dp[i][j] = dp[i][j-1] + 1
综上:
即 dp[i][j] = min(dp[i][j-1],dp[i-1][j],dp[i-1][j-1]) + 1
即如下图
class Solution:
def minDistance(self, word1: str, word2: str) -> int:
m = len(word1)
n = len(word2)
dp = [['_' for _ in range(n + 1)] for _ in range(m + 1)]
for i in range(n+1):
dp[0][i] = i
for j in range(m+1):
dp[j][0] = j
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]
else:
dp[i][j] = min(dp[i - 1][j - 1], min(dp[i - 1][j], dp[i][j - 1])) + 1
return dp[m][n]