LeetCode 题解工作台
两个字符串的删除操作
给定两个单词 word1 和 word2 ,返回使得 word1 和 word2 相同 所需的 最小步数 。 每步 可以删除任意一个字符串中的一个字符。 示例 1: 输入: word1 = "sea", word2 = "eat" 输出: 2 解释: 第一步将 "sea" 变为 "ea" ,第二步将…
2
题型
6
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
我们定义 表示使得字符串 的前 个字符和字符串 的前 个字符相同的最小删除步数。那么答案为 ,其中 和 分别是字符串 和 的长度。 初始时,如果 $j = 0$,那么 $f[i][0] = i$;如果 $i = 0$,那么 $f[0][j] = j$。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给定两个单词 word1 和 word2 ,返回使得 word1 和 word2 相同所需的最小步数。
每步 可以删除任意一个字符串中的一个字符。
示例 1:
输入: word1 = "sea", word2 = "eat" 输出: 2 解释: 第一步将 "sea" 变为 "ea" ,第二步将 "eat "变为 "ea"
示例 2:
输入:word1 = "leetcode", word2 = "etco" 输出:4
提示:
1 <= 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 i in range(1, m + 1):
f[i][0] = i
for j in range(1, n + 1):
f[0][j] = j
for i, a in enumerate(word1, 1):
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]) + 1
return f[m][n]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
The candidate understands dynamic programming concepts like state transitions and recursive relations.
- question_mark
The candidate should explain how they arrived at the minimum deletions by subtracting the LCS length from the total string lengths.
- question_mark
The candidate can efficiently describe time and space complexity in terms of the problem's constraints.
常见陷阱
外企场景- error
Confusing the problem with a subsequence matching problem without considering deletions.
- error
Overcomplicating the dynamic programming table and not explaining the base cases properly.
- error
Not considering edge cases like empty strings or strings with no common characters.
进阶变体
外企场景- arrow_right_alt
Variant 1: Finding the minimum steps to make the strings equal by inserting characters.
- arrow_right_alt
Variant 2: Extending this problem to consider insertions and deletions to make two strings identical.
- arrow_right_alt
Variant 3: Modifying the problem to allow character replacements in addition to deletions.