LeetCode 题解工作台
两个字符串的最小ASCII删除和
给定两个字符串 s1 和 s2 ,返回 使两个字符串相等所需删除字符的 ASCII 值的最小和 。 示例 1: 输入: s1 = "sea", s2 = "eat" 输出: 231 解释: 在 "sea" 中删除 "s" 并将 "s" 的值(115)加入总和。 在 "eat" 中删除 "t" 并将 …
2
题型
7
代码语言
3
相关题
当前训练重点
中等 · 状态·转移·动态规划
答案摘要
我们定义 表示使得 的前 个字符和 的前 个字符相等所需删除字符的 ASCII 值的最小和。那么答案就是 。 如果 $s_1[i-1] = s_2[j-1]$,那么 $f[i][j] = f[i-1][j-1]$。否则,我们可以删除 或者 中的一个,使得 达到最小。因此,状态转移方程如下:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路
题目描述
给定两个字符串s1 和 s2,返回 使两个字符串相等所需删除字符的 ASCII 值的最小和 。
示例 1:
输入: s1 = "sea", s2 = "eat" 输出: 231 解释: 在 "sea" 中删除 "s" 并将 "s" 的值(115)加入总和。 在 "eat" 中删除 "t" 并将 116 加入总和。 结束时,两个字符串相等,115 + 116 = 231 就是符合条件的最小和。
示例 2:
输入: s1 = "delete", s2 = "leet" 输出: 403 解释: 在 "delete" 中删除 "dee" 字符串变成 "let", 将 100[d]+101[e]+101[e] 加入总和。在 "leet" 中删除 "e" 将 101[e] 加入总和。 结束时,两个字符串都等于 "let",结果即为 100+101+101+101 = 403 。 如果改为将两个字符串转换为 "lee" 或 "eet",我们会得到 433 或 417 的结果,比答案更大。
提示:
1 <= s1.length, s2.length <= 1000s1和s2由小写英文字母组成
解题思路
方法一:动态规划
我们定义 表示使得 的前 个字符和 的前 个字符相等所需删除字符的 ASCII 值的最小和。那么答案就是 。
如果 ,那么 。否则,我们可以删除 或者 中的一个,使得 达到最小。因此,状态转移方程如下:
初始状态为 , 。
最后返回 即可。
时间复杂度 ,空间复杂度 。其中 和 分别是 和 的长度。
相似题目:
class Solution:
def minimumDeleteSum(self, s1: str, s2: str) -> int:
m, n = len(s1), len(s2)
f = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
f[i][0] = f[i - 1][0] + ord(s1[i - 1])
for j in range(1, n + 1):
f[0][j] = f[0][j - 1] + ord(s2[j - 1])
for i in range(1, m + 1):
for j in range(1, n + 1):
if s1[i - 1] == s2[j - 1]:
f[i][j] = f[i - 1][j - 1]
else:
f[i][j] = min(
f[i - 1][j] + ord(s1[i - 1]), f[i][j - 1] + ord(s2[j - 1])
)
return f[m][n]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for an understanding of dynamic programming and state transition techniques.
- question_mark
Evaluate the candidate's ability to break down the problem into smaller subproblems and apply recursion.
- question_mark
Assess how well the candidate handles base cases and memoization in dynamic programming solutions.
常见陷阱
外企场景- error
Failing to properly handle cases where characters match and not using optimal transitions.
- error
Not managing base cases correctly, leading to incorrect calculations in the dp table.
- error
Ignoring the need for memoization, which can result in exponential time complexity.
进阶变体
外企场景- arrow_right_alt
How would the approach change if the strings contained uppercase characters?
- arrow_right_alt
What if the characters in the strings were not restricted to lowercase English letters?
- arrow_right_alt
Can you optimize the space complexity by reducing the dp table size?