LeetCode 题解工作台
仅仅反转字母
给你一个字符串 s ,根据下述规则反转字符串: 所有非英文字母保留在原有位置。 所有英文字母(小写或大写)位置反转。 返回反转后的 s 。 示例 1: 输入: s = "ab-cd" 输出: "dc-ba" 示例 2: 输入: s = "a-bC-dEf-ghIj" 输出: "j-Ih-gfE-dC…
2
题型
6
代码语言
3
相关题
当前训练重点
简单 · 双·指针·invariant
答案摘要
我们用两个指针 和 分别指向字符串的头部和尾部。当 $i < j$ 时,我们不断地移动 和 ,直到 指向一个英文字母,并且 指向一个英文字母,然后交换 和 。最后返回字符串即可。 时间复杂度 ,空间复杂度 。其中 为字符串的长度。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 双·指针·invariant 题型思路
题目描述
给你一个字符串 s ,根据下述规则反转字符串:
- 所有非英文字母保留在原有位置。
- 所有英文字母(小写或大写)位置反转。
返回反转后的 s 。
示例 1:
输入:s = "ab-cd" 输出:"dc-ba"
示例 2:
输入:s = "a-bC-dEf-ghIj" 输出:"j-Ih-gfE-dCba"
示例 3:
输入:s = "Test1ng-Leet=code-Q!" 输出:"Qedo1ct-eeLg=ntse-T!"
提示
1 <= s.length <= 100s仅由 ASCII 值在范围[33, 122]的字符组成s不含'\"'或'\\'
解题思路
方法一:双指针
我们用两个指针 和 分别指向字符串的头部和尾部。当 时,我们不断地移动 和 ,直到 指向一个英文字母,并且 指向一个英文字母,然后交换 和 。最后返回字符串即可。
时间复杂度 ,空间复杂度 。其中 为字符串的长度。
class Solution:
def reverseOnlyLetters(self, s: str) -> str:
cs = list(s)
i, j = 0, len(cs) - 1
while i < j:
while i < j and not cs[i].isalpha():
i += 1
while i < j and not cs[j].isalpha():
j -= 1
if i < j:
cs[i], cs[j] = cs[j], cs[i]
i, j = i + 1, j - 1
return "".join(cs)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(N) |
| 空间 | O(N) |
面试官常问的追问
外企场景- question_mark
The candidate should clearly demonstrate an understanding of two-pointer techniques and its application to string manipulation.
- question_mark
Look for clarity in handling edge cases, such as strings with no alphabetic characters or strings where all characters are letters.
- question_mark
The candidate should be comfortable with explaining their thought process, particularly around skipping non-alphabetic characters while ensuring the overall time complexity is linear.
常见陷阱
外企场景- error
Failing to handle edge cases like an empty string or a string with no alphabetic characters.
- error
Not accounting for the fact that only letters need to be reversed, and other characters should remain in their original positions.
- error
Overcomplicating the solution by using additional data structures when a simple in-place swap suffices.
进阶变体
外企场景- arrow_right_alt
Reverse a string while only skipping digits.
- arrow_right_alt
Modify the problem to handle uppercase and lowercase letters differently.
- arrow_right_alt
Add more non-alphabetic characters like symbols, ensuring they remain in place during the reversal.