LeetCode 题解工作台
编辑距离
给你两个单词 word1 和 word2 , 请返回将 word1 转换成 word2 所使用的最少操作数 。 你可以对一个单词进行如下三种操作: 插入一个字符 删除一个字符 替换一个字符 示例 1: 输入: word1 = "horse", word2 = "ros" 输出: 3 解释: hors…
2
题型
6
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
我们定义 表示将 的前 个字符转换成 的前 个字符所使用的最少操作数。初始时 $f[i][0] = i$, $f[0][j] = j$。其中 $i \in [1, m], j \in [0, n]$。 考虑 :
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给你两个单词 word1 和 word2, 请返回将 word1 转换成 word2 所使用的最少操作数 。
你可以对一个单词进行如下三种操作:
- 插入一个字符
- 删除一个字符
- 替换一个字符
示例 1:
输入:word1 = "horse", word2 = "ros" 输出:3 解释: horse -> rorse (将 'h' 替换为 'r') rorse -> rose (删除 'r') rose -> ros (删除 'e')
示例 2:
输入:word1 = "intention", word2 = "execution" 输出:5 解释: intention -> inention (删除 't') inention -> enention (将 'i' 替换为 'e') enention -> exention (将 'n' 替换为 'x') exention -> exection (将 'n' 替换为 'c') exection -> execution (插入 'u')
提示:
0 <= word1.length, word2.length <= 500word1和word2由小写英文字母组成
解题思路
方法一:动态规划
我们定义 表示将 的前 个字符转换成 的前 个字符所使用的最少操作数。初始时 , 。其中 。
考虑 :
- 如果 ,那么我们只需要考虑将 的前 个字符转换成 的前 个字符所使用的最少操作数,因此 ;
- 否则,我们可以考虑插入、删除、替换操作,那么 。
综上,我们可以得到状态转移方程:
最后,我们返回 即可。
时间复杂度 ,空间复杂度 。其中 和 分别是 和 的长度。
class Solution:
def minDistance(self, word1: str, word2: str) -> int:
m, n = len(word1), len(word2)
f = [[0] * (n + 1) for _ in range(m + 1)]
for j in range(1, n + 1):
f[0][j] = j
for i, a in enumerate(word1, 1):
f[i][0] = i
for j, b in enumerate(word2, 1):
if a == b:
f[i][j] = f[i - 1][j - 1]
else:
f[i][j] = min(f[i - 1][j], f[i][j - 1], f[i - 1][j - 1]) + 1
return f[m][n]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(m _n) because each subproblem dp[i][j] is computed once, iterating through all i x j combinations. Space complexity is O(m_ n) for the full DP table, or O(min(m,n)) if optimized to store only one previous row, which is critical for long strings. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Asks how the DP table represents overlapping subproblems and why it's necessary.
- question_mark
Checks if you can optimize space for large input strings up to 500 characters.
- question_mark
Inquires about handling equal characters and how it affects the state transition.
常见陷阱
外企场景- error
Failing to initialize base cases correctly, leading to off-by-one errors in dp[0][j] or dp[i][0].
- error
Confusing insertion and deletion operations, which can produce incorrect minimal edits.
- error
Attempting recursive solutions without memoization, causing exponential time complexity and timeouts.
进阶变体
外企场景- arrow_right_alt
Compute edit distance with only insertions and deletions allowed, ignoring replacements.
- arrow_right_alt
Find all sequences of operations that achieve the minimum edit distance.
- arrow_right_alt
Apply edit distance to detect approximate string matching in a text or DNA sequence.