LeetCode 题解工作台
删除字符串两端相同字符后的最短长度
给你一个只包含字符 'a' , 'b' 和 'c' 的字符串 s ,你可以执行下面这个操作(5 个步骤)任意次: 选择字符串 s 一个 非空 的前缀,这个前缀的所有字符都相同。 选择字符串 s 一个 非空 的后缀,这个后缀的所有字符都相同。 前缀和后缀在字符串中任意位置都不能有交集。 前缀和后缀包含…
2
题型
7
代码语言
3
相关题
当前训练重点
中等 · 双·指针·invariant
答案摘要
我们定义两个指针 和 分别指向字符串 的头部和尾部,然后向中间移动,直到 和 指向的字符不相等,此时 $\max(0, j - i + 1)$ 即为答案。 时间复杂度 ,空间复杂度 。其中 为字符串 的长度。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 双·指针·invariant 题型思路
题目描述
给你一个只包含字符 'a','b' 和 'c' 的字符串 s ,你可以执行下面这个操作(5 个步骤)任意次:
- 选择字符串
s一个 非空 的前缀,这个前缀的所有字符都相同。 - 选择字符串
s一个 非空 的后缀,这个后缀的所有字符都相同。 - 前缀和后缀在字符串中任意位置都不能有交集。
- 前缀和后缀包含的所有字符都要相同。
- 同时删除前缀和后缀。
请你返回对字符串 s 执行上面操作任意次以后(可能 0 次),能得到的 最短长度 。
示例 1:
输入:s = "ca" 输出:2 解释:你没法删除任何一个字符,所以字符串长度仍然保持不变。
示例 2:
输入:s = "cabaabac" 输出:0 解释:最优操作序列为: - 选择前缀 "c" 和后缀 "c" 并删除它们,得到 s = "abaaba" 。 - 选择前缀 "a" 和后缀 "a" 并删除它们,得到 s = "baab" 。 - 选择前缀 "b" 和后缀 "b" 并删除它们,得到 s = "aa" 。 - 选择前缀 "a" 和后缀 "a" 并删除它们,得到 s = "" 。
示例 3:
输入:s = "aabccabba" 输出:3 解释:最优操作序列为: - 选择前缀 "aa" 和后缀 "a" 并删除它们,得到 s = "bccabb" 。 - 选择前缀 "b" 和后缀 "bb" 并删除它们,得到 s = "cca" 。
提示:
1 <= s.length <= 105s只包含字符'a','b'和'c'。
解题思路
方法一:双指针
我们定义两个指针 和 分别指向字符串 的头部和尾部,然后向中间移动,直到 和 指向的字符不相等,此时 即为答案。
时间复杂度 ,空间复杂度 。其中 为字符串 的长度。
class Solution:
def minimumLength(self, s: str) -> int:
i, j = 0, len(s) - 1
while i < j and s[i] == s[j]:
while i + 1 < j and s[i] == s[i + 1]:
i += 1
while i < j - 1 and s[j - 1] == s[j]:
j -= 1
i, j = i + 1, j - 1
return max(0, j - i + 1)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n) |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
Check if the candidate efficiently uses the two-pointer approach to minimize the number of steps.
- question_mark
Look for correct identification of the invariant and its application in halting further removals.
- question_mark
Evaluate how well the candidate handles edge cases, such as strings that cannot be reduced further.
常见陷阱
外企场景- error
Failing to correctly manage the two pointers, leading to an incorrect stopping condition.
- error
Overcomplicating the solution by using extra data structures when a simple two-pointer approach suffices.
- error
Not handling edge cases, such as strings where no removal is possible or when all characters are the same.
进阶变体
外企场景- arrow_right_alt
Handling larger inputs efficiently, ensuring the solution works for strings with up to 100,000 characters.
- arrow_right_alt
Adapting the solution to allow for different operations at each end (e.g., only removing matching prefixes).
- arrow_right_alt
Modifying the problem to allow removals from non-matching parts of the string rather than only from the ends.