583. 两个字符串的删除操作
- 思路
- example
- 最小步数
- 双串DP
dp[i][j]: word1 前i个,word2前j个 (word1: 0, ..., i-1; word2: 0, ..., j-1)
- 复杂度. 时间:O(mn), 空间: O(mn)
class Solution:
def minDistance(self, word1: str, word2: str) -> int:
m, n = len(word1), len(word2)
dp = [[0 for _ in range(n+1)] for _ in range(m+1)]
for j in range(1, n+1):
dp[0][j] = j
for i in range(1, m+1):
dp[i][0] = i
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], dp[i][j-1]) + 1
return dp[m][n]
72. 编辑距离
- 思路
- example
- 最少操作数
- 插入
- 删除
-
替换
dp[i][j]: 将word1[0,...,i-1] 转换成word2[0,...,j-1]所使用的最少操作数。
if (word1[i - 1] == word2[j - 1])
不操作
if (word1[i - 1] != word2[j - 1])
增
删
换
# 其实删和增可以“转换”,用一个case统一即可。
class Solution:
def minDistance(self, word1: str, word2: str) -> int:
m, n = len(word1), len(word2)
dp = [[0 for _ in range(n+1)] for _ in range(m+1)]
for i in range(m+1):
dp[i][0] = i
for j in range(n+1):
dp[0][j] = 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], dp[i-1][j], dp[i][j-1]) + 1
# 替换 插入/删除统一处理:有两种情况
return dp[m][n]
-
如果需要保存最佳操作
编辑距离问题 小结
- TBA
code