LeetCode 题解工作台
用特殊操作处理字符串 I
给你一个字符串 s ,它由小写英文字母和特殊字符: * 、 # 和 % 组成。 请根据以下规则从左到右处理 s 中的字符,构造一个新的字符串 result : 如果字符是 小写 英文字母,则将其添加到 result 中。 字符 '*' 会 删除 result 中的最后一个字符(如果存在)。 字符 '…
2
题型
5
代码语言
3
相关题
当前训练重点
中等 · string·结合·模拟
答案摘要
我们直接模拟题目中的操作即可。我们使用一个列表 来存储当前的结果字符串。遍历输入字符串 中的每个字符,根据字符的类型执行相应的操作: - 如果字符是小写英文字母,则将其添加到 中。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 string·结合·模拟 题型思路
题目描述
给你一个字符串 s,它由小写英文字母和特殊字符:*、# 和 % 组成。
请根据以下规则从左到右处理 s 中的字符,构造一个新的字符串 result:
- 如果字符是 小写 英文字母,则将其添加到
result中。 - 字符
'*'会 删除result中的最后一个字符(如果存在)。 - 字符
'#'会 复制 当前的result并 追加 到其自身后面。 - 字符
'%'会 反转 当前的result。
在处理完 s 中的所有字符后,返回最终的字符串 result。
示例 1:
输入: s = "a#b%*"
输出: "ba"
解释:
i |
s[i] |
操作 | 当前 result |
|---|---|---|---|
| 0 | 'a' |
添加 'a' |
"a" |
| 1 | '#' |
复制 result |
"aa" |
| 2 | 'b' |
添加 'b' |
"aab" |
| 3 | '%' |
反转 result |
"baa" |
| 4 | '*' |
删除最后一个字符 | "ba" |
因此,最终的 result 是 "ba"。
示例 2:
输入: s = "z*#"
输出: ""
解释:
i |
s[i] |
操作 | 当前 result |
|---|---|---|---|
| 0 | 'z' |
添加 'z' |
"z" |
| 1 | '*' |
删除最后一个字符 | "" |
| 2 | '#' |
复制字符串 | "" |
因此,最终的 result 是 ""。
提示:
1 <= s.length <= 20s只包含小写英文字母和特殊字符*、#和%。
解题思路
方法一:模拟
我们直接模拟题目中的操作即可。我们使用一个列表 来存储当前的结果字符串。遍历输入字符串 中的每个字符,根据字符的类型执行相应的操作:
- 如果字符是小写英文字母,则将其添加到 中。
- 如果字符是
*,则删除 中的最后一个字符(如果存在)。 - 如果字符是
#,则将 复制一遍并追加到其自身后面。 - 如果字符是
%,则反转 。
最后,我们将 转换为字符串并返回。
时间复杂度 ,其中 是字符串 的长度。最坏情况下,可能会因为 # 操作导致 的长度每次翻倍,因此时间复杂度是指数级的。忽略答案的空间消耗,空间复杂度 。
class Solution:
def processStr(self, s: str) -> str:
result = []
for c in s:
if c.isalpha():
result.append(c)
elif c == "*" and result:
result.pop()
elif c == "#":
result.extend(result)
elif c == "%":
result.reverse()
return "".join(result)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
The candidate's approach to handling special characters efficiently will be crucial.
- question_mark
Watch for edge case handling, especially with consecutive special characters or empty results.
- question_mark
Evaluate the candidate's ability to simplify string transformations and optimize space usage.
常见陷阱
外企场景- error
Forgetting to handle consecutive special characters or operations like * correctly.
- error
Not considering edge cases, such as when the string starts or ends with special characters.
- error
Inefficient handling of the string leading to higher time or space complexities.
进阶变体
外企场景- arrow_right_alt
Modify the rules for * and # to have different effects (e.g., # removes multiple previous characters).
- arrow_right_alt
Process the string in reverse order and observe any difference in the final result.
- arrow_right_alt
Introduce additional special characters to simulate more complex string transformations.