LeetCode 题解工作台
反转字符串 II
给定一个字符串 s 和一个整数 k ,从字符串开头算起,每计数至 2k 个字符,就反转这 2k 字符中的前 k 个字符。 如果剩余字符少于 k 个,则将剩余字符全部反转。 如果剩余字符小于 2k 但大于或等于 k 个,则反转前 k 个字符,其余字符保持原样。 示例 1: 输入: s = "abcde…
2
题型
5
代码语言
3
相关题
当前训练重点
简单 · 双·指针·invariant
答案摘要
我们可以遍历字符串 ,每次遍历 个字符,然后利用双指针技巧,对这 个字符中的前 个字符进行反转。 时间复杂度 ,空间复杂度 。其中 为字符串 的长度。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 双·指针·invariant 题型思路
题目描述
给定一个字符串 s 和一个整数 k,从字符串开头算起,每计数至 2k 个字符,就反转这 2k 字符中的前 k 个字符。
- 如果剩余字符少于
k个,则将剩余字符全部反转。 - 如果剩余字符小于
2k但大于或等于k个,则反转前k个字符,其余字符保持原样。
示例 1:
输入:s = "abcdefg", k = 2 输出:"bacdfeg"
示例 2:
输入:s = "abcd", k = 2 输出:"bacd"
提示:
1 <= s.length <= 104s仅由小写英文组成1 <= k <= 104
解题思路
方法一:双指针
我们可以遍历字符串 ,每次遍历 个字符,然后利用双指针技巧,对这 个字符中的前 个字符进行反转。
时间复杂度 ,空间复杂度 。其中 为字符串 的长度。
class Solution:
def reverseStr(self, s: str, k: int) -> str:
cs = list(s)
for i in range(0, len(cs), 2 * k):
cs[i : i + k] = reversed(cs[i : i + k])
return "".join(cs)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(N) because each character is visited at most once during the swaps. Space complexity is O(N) if using a character array for in-place swaps; otherwise, extra space is minimal beyond the original string. |
| 空间 | O(N) |
面试官常问的追问
外企场景- question_mark
Look for proper handling of blocks smaller than k to test boundary understanding.
- question_mark
Ensure the candidate uses two pointers rather than naive slicing to avoid extra memory usage.
- question_mark
Watch if the candidate correctly iterates in 2k steps rather than per-character to maintain efficiency.
常见陷阱
外企场景- error
Reversing more than k characters in a 2k block and corrupting the second half.
- error
Failing to handle the last partial segment correctly when its length is less than k.
- error
Using string concatenation inside loops, leading to O(N^2) time instead of O(N).
进阶变体
外企场景- arrow_right_alt
Reverse every first k characters in 3k blocks instead of 2k, requiring adjusted pointer increments.
- arrow_right_alt
Perform conditional reversal based on character type (e.g., vowels only) while keeping the 2k block pattern.
- arrow_right_alt
Apply the same two-pointer invariant logic to an array of integers instead of a string.