LeetCode 题解工作台

反转字符串

编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 s 的形式给出。 不要给另外的数组分配额外的空间,你必须 原地 修改输入数组 、使用 O(1) 的额外空间解决这一问题。 示例 1: 输入: s = ["h","e","l","l","o"] 输出: ["o","l","l","e…

category

2

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 双·指针·invariant

bolt

答案摘要

我们用两个指针 和 ,初始时分别指向数组的首尾,每次将 和 对应的元素交换,然后 向后移动, 向前移动,直到 和 相遇。 时间复杂度 ,其中 是数组的长度。空间复杂度 。

Interview AiBox logo

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

试试 AiBox 面试助手arrow_forward
description

题目描述

编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 s 的形式给出。

不要给另外的数组分配额外的空间,你必须原地修改输入数组、使用 O(1) 的额外空间解决这一问题。

 

示例 1:

输入:s = ["h","e","l","l","o"]
输出:["o","l","l","e","h"]

示例 2:

输入:s = ["H","a","n","n","a","h"]
输出:["h","a","n","n","a","H"]

 

提示:

  • 1 <= s.length <= 105
  • s[i] 都是 ASCII 码表中的可打印字符
lightbulb

解题思路

方法一:双指针

我们用两个指针 iijj,初始时分别指向数组的首尾,每次将 iijj 对应的元素交换,然后 ii 向后移动,jj 向前移动,直到 iijj 相遇。

时间复杂度 O(n)O(n),其中 nn 是数组的长度。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
class Solution:
    def reverseString(self, s: List[str]) -> None:
        i, j = 0, len(s) - 1
        while i < j:
            s[i], s[j] = s[j], s[i]
            i, j = i + 1, j - 1
speed

复杂度分析

指标
时间complexity is O(n) because each character is visited once in a single pass. Space complexity is O(1) since all swaps are in-place and no additional arrays are created.
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Looks for correct two-pointer initialization and proper index tracking.

  • question_mark

    Checks that swaps are performed in-place without auxiliary storage.

  • question_mark

    Tests edge cases like empty arrays or arrays with one character.

warning

常见陷阱

外企场景
  • error

    Forgetting to move both pointers after a swap, causing infinite loops.

  • error

    Using extra arrays instead of in-place modification.

  • error

    Mismanaging indices, leading to off-by-one errors or partial reversal.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Reverse a linked list using two-pointer or recursive swapping.

  • arrow_right_alt

    Reverse only a substring or a section of the array in-place.

  • arrow_right_alt

    Reverse words in a sentence while maintaining character order within words.

help

常见问题

外企场景

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