LeetCode 题解工作台
反转字符串
编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 s 的形式给出。 不要给另外的数组分配额外的空间,你必须 原地 修改输入数组 、使用 O(1) 的额外空间解决这一问题。 示例 1: 输入: s = ["h","e","l","l","o"] 输出: ["o","l","l","e…
2
题型
7
代码语言
3
相关题
当前训练重点
简单 · 双·指针·invariant
答案摘要
我们用两个指针 和 ,初始时分别指向数组的首尾,每次将 和 对应的元素交换,然后 向后移动, 向前移动,直到 和 相遇。 时间复杂度 ,其中 是数组的长度。空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 双·指针·invariant 题型思路
题目描述
解题思路
方法一:双指针
我们用两个指针 和 ,初始时分别指向数组的首尾,每次将 和 对应的元素交换,然后 向后移动, 向前移动,直到 和 相遇。
时间复杂度 ,其中 是数组的长度。空间复杂度 。
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
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | 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 |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.