⚡Flashcard Drill➔
NeetCode #189LC-557EasyTwo Pointers
← Back to All Problems

#189 · #557 · Reverse Words in a String III(反转字符串中的单词 III)

📌 Problem Statement & Constraints

Given a string s, reverse the order of characters in each word while keeping the word order and the single spaces between words. Constraints: 1 <= s.length <= 5 * 10^4; s contains printable ASCII characters without leading or trailing spaces and with single spaces between words.

💡 Core Algorithmic Approaches

  1. Split on spaces, reverse each word, and rejoin.
  2. A more memory-conscious version walks the string, finds each word's boundaries, and writes its characters in reverse into a result buffer.
  3. The split-and-join version is O(n) and far clearer; only reach for the in-place variant if the input is a mutable character array.
  4. Note that this is different from reversing the whole string or reversing the word order.

💻 Benchmark Python3 Implementation

class Solution:
    def reverseWords(self, s: str) -> str:
        return " ".join(w[::-1] for w in s.split(" "))


# In-place variant for a mutable character array
class Solution2:
    def reverseWords(self, s: List[str]) -> None:
        n = len(s)
        start = 0
        for i in range(n + 1):         # n acts as the end sentinel
            if i == n or s[i] == " ":
                lo, hi = start, i - 1
                while lo < hi:
                    s[lo], s[hi] = s[hi], s[lo]
                    lo += 1
                    hi -= 1
                start = i + 1

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): each character is touched once (the split version additionally allocates the word list).
💾 Space Complexity
O(n) for the result; O(1) extra for the in-place variant.

⚠️ Interview Pitfalls & Follow-ups

  • Reversing the word order as well: the problem only reverses the characters within each word.
  • Splitting on whitespace with s.split(): that collapses runs of spaces; here single spaces are guaranteed, so either form works, but split(" ") is the literal reading.
  • Forgetting the end sentinel in the in-place version: the final word would never be reversed.
  • Trying to reverse in place when s is an immutable string: strings cannot be mutated; a list of characters or a rebuilt string is required.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Two Pointers Problems

中文速览与面试要点

反转字符串中的单词 III

给定一个字符串 s,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。约束:1 ≤ s.length ≤ 5 × 10^4;s 包含可打印的 ASCII 字符;s 不包含任何开头或结尾空格;s 里至少有一个单词;s 中的所有单词都用一个空格隔开。

核心要点

  • 切分 + 逐词反转(标准解) :按空格切分,对每个单词用切片 [::-1] 反转,再用空格拼回。
  • 注意与 151、186 的区别 :151 是 反转单词顺序 ("the sky" → "sky the");本题是 反转每个单词内部 ("the sky" → "eht yks")。186 是本题的原地字符数组版本。
  • 原地写法(若输入是字符数组) :用双指针定位每个单词的边界,对每个单词做原地反转。
  • 复杂度 :O(n) 时间。

常见陷阱

  • 与 151 题混淆 :151 反转的是 单词顺序 ,本题反转的是 单词内部字符 。两者目标完全不同。
  • 用 split(" ") 而非 split() :题目保证单词间恰好一个空格,两者等价;但用 split() 更稳健(能处理多余空格)。
  • 手动用循环逐字符反转 : w[::-1] 是 C 层实现,远快于 Python 层的循环。
  • 忘记用空格重新拼接 : "".join(...) 会把所有单词粘连在一起。

参考实现

class Solution:
    def reverseWords(self, s: str) -> str:
        return ' '.join(w[::-1] for w in s.split())

# 原地写法(适用于字符数组输入,O(1) 额外空间):
# s = list(s)
# start = 0
# for i in range(len(s) + 1):
#     if i == len(s) or s[i] == ' ':
#         lo, hi = start, i - 1
#         while lo < hi:
#             s[lo], s[hi] = s[hi], s[lo]
#             lo += 1; hi -= 1
#         start = i + 1
# return ''.join(s)