LeetCode 题解工作台

反转字符串 II

给定一个字符串 s 和一个整数 k ,从字符串开头算起,每计数至 2k 个字符,就反转这 2k 字符中的前 k 个字符。 如果剩余字符少于 k 个,则将剩余字符全部反转。 如果剩余字符小于 2k 但大于或等于 k 个,则反转前 k 个字符,其余字符保持原样。 示例 1: 输入: s = "abcde…

category

2

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 双·指针·invariant

bolt

答案摘要

我们可以遍历字符串 ,每次遍历 个字符,然后利用双指针技巧,对这 个字符中的前 个字符进行反转。 时间复杂度 ,空间复杂度 。其中 为字符串 的长度。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 双·指针·invariant 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给定一个字符串 s 和一个整数 k,从字符串开头算起,每计数至 2k 个字符,就反转这 2k 字符中的前 k 个字符。

  • 如果剩余字符少于 k 个,则将剩余字符全部反转。
  • 如果剩余字符小于 2k 但大于或等于 k 个,则反转前 k 个字符,其余字符保持原样。

 

示例 1:

输入:s = "abcdefg", k = 2
输出:"bacdfeg"

示例 2:

输入:s = "abcd", k = 2
输出:"bacd"

 

提示:

  • 1 <= s.length <= 104
  • s 仅由小写英文组成
  • 1 <= k <= 104
lightbulb

解题思路

方法一:双指针

我们可以遍历字符串 s\textit{s},每次遍历 2k\textit{2k} 个字符,然后利用双指针技巧,对这 2k\textit{2k} 个字符中的前 k\textit{k} 个字符进行反转。

时间复杂度 O(n)O(n),空间复杂度 O(n)O(n)。其中 nn 为字符串 s\textit{s} 的长度。

1
2
3
4
5
6
7
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)
speed

复杂度分析

指标
时间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)
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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).

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

反转字符串 II题解:双·指针·invariant | LeetCode #541 简单