LeetCode 题解工作台
故障键盘
你的笔记本键盘存在故障,每当你在上面输入字符 'i' 时,它会反转你所写的字符串。而输入其他字符则可以正常工作。 给你一个下标从 0 开始的字符串 s ,请你用故障键盘依次输入每个字符。 返回最终笔记本屏幕上输出的字符串。 示例 1: 输入: s = "string" 输出: "rtsng" 解释:…
2
题型
6
代码语言
3
相关题
当前训练重点
简单 · string·结合·模拟
答案摘要
我们直接模拟键盘的输入过程,用一个字符数组 来记录屏幕上的文本,初始时 为空。 对于字符串 中的每个字符 ,如果 不是字符 ,那么我们将 加入到 的末尾;否则我们将 中的所有字符反转。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 string·结合·模拟 题型思路
题目描述
你的笔记本键盘存在故障,每当你在上面输入字符 'i' 时,它会反转你所写的字符串。而输入其他字符则可以正常工作。
给你一个下标从 0 开始的字符串 s ,请你用故障键盘依次输入每个字符。
返回最终笔记本屏幕上输出的字符串。
示例 1:
输入:s = "string" 输出:"rtsng" 解释: 输入第 1 个字符后,屏幕上的文本是:"s" 。 输入第 2 个字符后,屏幕上的文本是:"st" 。 输入第 3 个字符后,屏幕上的文本是:"str" 。 因为第 4 个字符是 'i' ,屏幕上的文本被反转,变成 "rts" 。 输入第 5 个字符后,屏幕上的文本是:"rtsn" 。 输入第 6 个字符后,屏幕上的文本是: "rtsng" 。 因此,返回 "rtsng" 。
示例 2:
输入:s = "poiinter" 输出:"ponter" 解释: 输入第 1 个字符后,屏幕上的文本是:"p" 。 输入第 2 个字符后,屏幕上的文本是:"po" 。 因为第 3 个字符是 'i' ,屏幕上的文本被反转,变成 "op" 。 因为第 4 个字符是 'i' ,屏幕上的文本被反转,变成 "po" 。 输入第 5 个字符后,屏幕上的文本是:"pon" 。 输入第 6 个字符后,屏幕上的文本是:"pont" 。 输入第 7 个字符后,屏幕上的文本是:"ponte" 。 输入第 8 个字符后,屏幕上的文本是:"ponter" 。 因此,返回 "ponter" 。
提示:
1 <= s.length <= 100s由小写英文字母组成s[0] != 'i'
解题思路
方法一:模拟
我们直接模拟键盘的输入过程,用一个字符数组 来记录屏幕上的文本,初始时 为空。
对于字符串 中的每个字符 ,如果 不是字符 ,那么我们将 加入到 的末尾;否则我们将 中的所有字符反转。
最终答案即为 中的字符组成的字符串。
时间复杂度 ,空间复杂度 。其中 是字符串 的长度。
class Solution:
def finalString(self, s: str) -> str:
t = []
for c in s:
if c == "i":
t = t[::-1]
else:
t.append(c)
return "".join(t)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) because each character is processed once and reversals on a mutable list are O(n). Space complexity is O(n) to store the intermediate string during simulation. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Checks if you understand how to simulate character effects on strings efficiently.
- question_mark
Wants to see proper handling of the reversal trigger 'i' and non-destructive string operations.
- question_mark
Assesses your ability to maintain order and correctness during iterative string manipulations.
常见陷阱
外企场景- error
Attempting to reverse strings using concatenation in a loop, which can increase time complexity.
- error
Forgetting to reverse the string each time an 'i' appears, leading to incorrect final output.
- error
Not handling edge cases like consecutive 'i' characters or the first character being 'i'.
进阶变体
外企场景- arrow_right_alt
Change the reversal trigger character from 'i' to another letter or symbol.
- arrow_right_alt
Instead of reversing the whole string, reverse only the last k characters each time.
- arrow_right_alt
Apply similar simulation on an array of numbers where a specific value triggers a reversal.