LeetCode 题解工作台
删除星号以后字典序最小的字符串
给你一个字符串 s 。它可能包含任意数量的 '*' 字符。你的任务是删除所有的 '*' 字符。 当字符串还存在至少一个 '*' 字符时,你可以执行以下操作: 删除最左边的 '*' 字符,同时删除该星号字符左边一个字典序 最小 的字符。如果有多个字典序最小的字符,你可以删除它们中的任意一个。 请你返回…
5
题型
7
代码语言
3
相关题
当前训练重点
中等 · 栈·状态
答案摘要
我们定义一个数组 ,用于记录每个字符的下标列表,定义一个长度为 的布尔数组 ,用于记录每个字符是否需要删除。 遍历字符串 :
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 栈·状态 题型思路
题目描述
给你一个字符串 s 。它可能包含任意数量的 '*' 字符。你的任务是删除所有的 '*' 字符。
当字符串还存在至少一个 '*' 字符时,你可以执行以下操作:
- 删除最左边的
'*'字符,同时删除该星号字符左边一个字典序 最小 的字符。如果有多个字典序最小的字符,你可以删除它们中的任意一个。
请你返回删除所有 '*' 字符以后,剩余字符连接而成的 字典序最小 的字符串。
示例 1:
输入:s = "aaba*"
输出:"aab"
解释:
删除 '*' 号和它左边的其中一个 'a' 字符。如果我们选择删除 s[3] ,s 字典序最小。
示例 2:
输入:s = "abc"
输出:"abc"
解释:
字符串中没有 '*' 字符。
提示:
1 <= s.length <= 105s只含有小写英文字母和'*'字符。- 输入保证操作可以删除所有的
'*'字符。
解题思路
方法一:按字符记录下标
我们定义一个数组 ,用于记录每个字符的下标列表,定义一个长度为 的布尔数组 ,用于记录每个字符是否需要删除。
遍历字符串 :
如果当前字符是星号,我们就需要删除它,因此我们将 标记为已删除。同时,我们需要删除此时字典序最小且下标最大的字符。我们从小到大遍历 个小写字母,如果 不为空,我们就删除 中的最后一个下标,并将 中对应的下标置为已删除。
如果当前字符不是星号,我们就将当前字符的下标加入 中。
最后,我们遍历 ,将未删除的字符拼接起来即可。
时间复杂度 ,空间复杂度 。其中 为字符串 的长度,而 为字符集大小,本题中 。
class Solution:
def clearStars(self, s: str) -> str:
g = defaultdict(list)
n = len(s)
rem = [False] * n
for i, c in enumerate(s):
if c == "*":
rem[i] = True
for a in ascii_lowercase:
if g[a]:
rem[g[a].pop()] = True
break
else:
g[c].append(i)
return "".join(c for i, c in enumerate(s) if not rem[i])
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n * |Σ|) because each character is pushed or popped once and comparisons may involve the alphabet size. Space complexity is O(n + |Σ|) for the stack and hash tables used to track character frequencies or positions. |
| 空间 | O(n + |
面试官常问的追问
外企场景- question_mark
Expect candidates to manage stack operations accurately under '*' deletions.
- question_mark
Look for awareness of lexicographical order when deciding which characters to remove.
- question_mark
Check that the solution scales efficiently with large strings up to length 10^5.
常见陷阱
外企场景- error
Failing to correctly pop the last character for each '*', breaking lexicographical order.
- error
Ignoring edge cases where multiple consecutive '*' appear.
- error
Attempting to sort after all removals instead of maintaining order during processing.
进阶变体
外企场景- arrow_right_alt
Return the lexicographically largest string after removing stars using the same pattern.
- arrow_right_alt
Allow additional operations such as replacing letters with '*', still requiring minimal result.
- arrow_right_alt
Process strings with Unicode characters, maintaining lexicographical ordering and stack logic.