https://leetcode-cn.com/problems/edit-distance/
https://leetcode-cn.com/problems/edit-distance/solution/bian-ji-ju-chi-by-leetcode-solution/
状态拆解为3个状态,进行分析:
对“dp[i-1][j-1] 表示替换操作,dp[i-1][j] 表示删除操作,dp[i][j-1] 表示插入操作。”的补充理解:
以 word1 为 “horse”,word2 为 “ros”,且 dp[5][3] 为例,即要将 word1的前 5 个字符转换为 word2的前 3 个字符,也就是将 horse 转换为 ros,因此有:
dp初始状态:
状态转移方程:
class Solution: def minDistance(self, word1: str, word2: str) -> int: n,m = len(word1),len(word2) if n * m == 0:# 有一个字符串为空串 return n + m D = [ [0] * (m + 1) for _ in range(n + 1)] # 边界状态初始化 for i in range(n + 1): D[i][0] = i for j in range(m + 1): D[0][j] = j # 计算所有 DP 值 for i in range(1, n + 1): for j in range(1, m + 1): if word1[i - 1] != word2[j - 1]: D[i][j]=min(D[i-1][j]+1,D[i][j-1]+1,D[i-1][j-1]+1) else: D[i][j]=min(D[i-1][j]+1,D[i][j-1]+1,D[i-1][j-1]) return D[n][m]