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
- Split on spaces, reverse each word, and rejoin.
- A more memory-conscious version walks the string, finds each word's boundaries, and writes its characters in reverse into a result buffer.
- 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.
- 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, butsplit(" ")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
sis an immutable string: strings cannot be mutated; a list of characters or a rebuilt string is required.