LeetCode 题解工作台
反转字符串中的单词
给你一个字符串 s ,请你反转字符串中 单词 的顺序。 单词 是由非空格字符组成的字符串。 s 中使用至少一个空格将字符串中的 单词 分隔开。 返回 单词 顺序颠倒且 单词 之间用单个空格连接的结果字符串。 注意: 输入字符串 s 中可能会存在前导空格、尾随空格或者单词间的多个空格。返回的结果字符串…
2
题型
7
代码语言
3
相关题
当前训练重点
中等 · 双·指针·invariant
答案摘要
我们可以使用双指针 和 ,每次找到一个单词,将其添加到结果列表中,最后将结果列表反转,再拼接成字符串即可。 时间复杂度 ,空间复杂度 。其中 为字符串的长度。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 双·指针·invariant 题型思路
题目描述
给你一个字符串 s ,请你反转字符串中 单词 的顺序。
单词 是由非空格字符组成的字符串。s 中使用至少一个空格将字符串中的 单词 分隔开。
返回 单词 顺序颠倒且 单词 之间用单个空格连接的结果字符串。
注意:输入字符串 s中可能会存在前导空格、尾随空格或者单词间的多个空格。返回的结果字符串中,单词间应当仅用单个空格分隔,且不包含任何额外的空格。
示例 1:
输入:s = "the sky is blue" 输出:"blue is sky the"
示例 2:
输入:s = " hello world " 输出:"world hello" 解释:反转后的字符串中不能存在前导空格和尾随空格。
示例 3:
输入:s = "a good example" 输出:"example good a" 解释:如果两个单词间有多余的空格,反转后的字符串需要将单词间的空格减少到仅有一个。
提示:
1 <= s.length <= 104s包含英文大小写字母、数字和空格' 's中 至少存在一个 单词
进阶:如果字符串在你使用的编程语言中是一种可变数据类型,请尝试使用 O(1) 额外空间复杂度的 原地 解法。
解题思路
方法一:双指针
我们可以使用双指针 和 ,每次找到一个单词,将其添加到结果列表中,最后将结果列表反转,再拼接成字符串即可。
时间复杂度 ,空间复杂度 。其中 为字符串的长度。
class Solution:
def reverseWords(self, s: str) -> str:
words = []
i, n = 0, len(s)
while i < n:
while i < n and s[i] == " ":
i += 1
if i < n:
j = i
while j < n and s[j] != " ":
j += 1
words.append(s[i:j])
i = j
return " ".join(words[::-1])
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n) because each character is scanned at most twice during trimming and reversal. Space complexity is O(n) if a new string is constructed, or O(1) extra if in-place operations are performed with careful pointer management. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Watch for hidden leading and trailing spaces in the input string.
- question_mark
Check if candidates correctly reduce multiple spaces between words to a single space.
- question_mark
Ensure candidates use a two-pointer approach rather than naive split and reverse methods.
常见陷阱
外企场景- error
Failing to trim leading or trailing spaces before scanning.
- error
Incorrectly handling multiple consecutive spaces between words.
- error
Building the output string with extra spaces at the start or end.
进阶变体
外企场景- arrow_right_alt
Reverse words in a string in-place without allocating extra arrays.
- arrow_right_alt
Handle Unicode or non-ASCII whitespace characters during reversal.
- arrow_right_alt
Reverse words while preserving the original capitalization or punctuation.