LeetCode 题解工作台
反转单词前缀
给你一个下标从 0 开始的字符串 word 和一个字符 ch 。找出 ch 第一次出现的下标 i , 反转 word 中从下标 0 开始、直到下标 i 结束(含下标 i )的那段字符。如果 word 中不存在字符 ch ,则无需进行任何操作。 例如,如果 word = "abcdefd" 且 ch …
3
题型
7
代码语言
3
相关题
当前训练重点
简单 · 双·指针·invariant
答案摘要
我们先找到字符 第一次出现的下标 ,然后反转从下标 开始、直到下标 结束(含下标 )的那段字符,最后将反转后的字符串与下标 $i + 1$ 开始的字符串拼接即可。 时间复杂度 ,空间复杂度 。其中 为字符串 的长度。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 双·指针·invariant 题型思路
题目描述
给你一个下标从 0 开始的字符串 word 和一个字符 ch 。找出 ch 第一次出现的下标 i ,反转 word 中从下标 0 开始、直到下标 i 结束(含下标 i )的那段字符。如果 word 中不存在字符 ch ,则无需进行任何操作。
- 例如,如果
word = "abcdefd"且ch = 'd',那么你应该 反转 从下标 0 开始、直到下标3结束(含下标3)。结果字符串将会是"dcbaefd"。
返回 结果字符串 。
示例 1:
输入:word = "abcdefd", ch = 'd' 输出:"dcbaefd" 解释:"d" 第一次出现在下标 3 。 反转从下标 0 到下标 3(含下标 3)的这段字符,结果字符串是 "dcbaefd" 。
示例 2:
输入:word = "xyxzxe", ch = 'z' 输出:"zxyxxe" 解释:"z" 第一次也是唯一一次出现是在下标 3 。 反转从下标 0 到下标 3(含下标 3)的这段字符,结果字符串是 "zxyxxe" 。
示例 3:
输入:word = "abcd", ch = 'z' 输出:"abcd" 解释:"z" 不存在于 word 中。 无需执行反转操作,结果字符串是 "abcd" 。
提示:
1 <= word.length <= 250word由小写英文字母组成ch是一个小写英文字母
解题思路
方法一:模拟
我们先找到字符 第一次出现的下标 ,然后反转从下标 开始、直到下标 结束(含下标 )的那段字符,最后将反转后的字符串与下标 开始的字符串拼接即可。
时间复杂度 ,空间复杂度 。其中 为字符串 的长度。
class Solution:
def reversePrefix(self, word: str, ch: str) -> str:
i = word.find(ch)
return word if i == -1 else word[i::-1] + word[i + 1 :]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(n) |
| 空间 | O(n) |
面试官常问的追问
外企场景- question_mark
Candidate can quickly identify the problem's two-pointer scanning approach.
- question_mark
Candidate efficiently handles cases where the target character does not exist in the string.
- question_mark
Candidate implements the in-place reversal technique without using unnecessary extra space.
常见陷阱
外企场景- error
Failing to handle the case where the target character does not exist in the string.
- error
Not reversing the string in place, leading to extra space usage.
- error
Overcomplicating the solution by using additional data structures instead of two-pointer scanning.
进阶变体
外企场景- arrow_right_alt
Consider handling multiple occurrences of the target character and reversing up to the last occurrence.
- arrow_right_alt
Extend the problem by allowing the user to reverse the segment up to a specified index instead of just the first occurrence.
- arrow_right_alt
Consider reversing substrings from any starting index to a given character index.