The most straightforward approach splits the string into individual words, reverses each word separately, then joins them back together. By treating each word as an independent unit, we can use built-in string reversal methods on each one. This approach is simple to understand but requires extra space for the split words.
Instead of splitting into an array, we can build the result string character by character. As we scan through the input, we accumulate characters for each word in reverse order by prepending each new character. When we hit a space, we append the reversed word to our result and reset for the next word. This avoids explicit array operations but involves string concatenation.
tmp_str and an empty result string res.tmp_str to res, then clear tmp_str.res.tmp_str (building the word in reverse).res.We can reverse each word in place by identifying word boundaries and using two pointers to swap characters within each word. As we scan through the string, we track where each word starts. When we encounter a space or reach the end, we know the word boundaries and can reverse that segment. This approach modifies a character array copy of the string directly.
l to track the start of the current word.r through the array:r reaches a space or the end of the string, we have found a complete word.l to r + 1 for the next word.class Solution:
def reverseWords(self, s: str) -> str:
s = list(s)
l = 0
for r in range(len(s)):
if s[r] == " " or r == len(s) - 1:
temp_l, temp_r = l, r - 1 if s[r] == " " else r
while temp_l < temp_r:
s[temp_l], s[temp_r] = s[temp_r], s[temp_l]
temp_l += 1
temp_r -= 1
l = r + 1
return "".join(s)This is a cleaner variation of the two-pointer approach. Instead of checking for word boundaries at every position, we explicitly find each word by scanning for non-space characters. Once we locate a word's start, we scan to find its end, reverse the word in place, then jump to the next word. This makes the logic more explicit and easier to follow.
i:j to find where the word ends (next space or end of array).i and j - 1.i to j to continue with the next word.class Solution:
def reverseWords(self, s: str) -> str:
def reverse(i, j):
while i < j:
s[i], s[j] = s[j], s[i]
i += 1
j -= 1
s = list(s)
i = 0
while i < len(s):
if s[i] != ' ':
j = i
while j < len(s) and s[j] != ' ':
j += 1
reverse(i, j - 1)
i = j + 1
return ''.join(s)When iterating through the string looking for spaces to identify word boundaries, the last word has no trailing space. A common mistake is failing to reverse the final word because the loop only triggers reversal when encountering a space character.
In languages where strings are immutable (like Python, Java, and JavaScript), attempting to modify the string in place will fail. You must first convert the string to a mutable data structure like a character array, perform the reversals, then convert back to a string.