Problem
Given an input string, reverse the string word by word.
Example 1:
1 |
|
Example 2:
1 |
|
Example 3:
1 |
|
Note:
- A word is defined as a sequence of non-space characters.
- Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces.
- You need to reduce multiple spaces between two words to a single space in the reversed string.
Follow up:
For C programmers, try to solve it in-place in O(1) extra space.
Explanation 1
-
If we do this problem without programming, first we would split each word no matter how many spaces in between each word. We can use
replaceAll
to replace more than one space into one space, thensplit
by space. -
Now, we have an array of many words, and we want to put the last whole word at the beginning, second last whole word in the second position, etc. We can simply loop from the end to beginning, and put each element (word) into the stringbuilder. At the end, we can just return this stringbuilder as string.
Solution 1.1
1 |
|
Solution 1.2
1 |
|
Explanation 2
-
We can create two pointers
start
andend
point to a word’s beginning index and end index (exclusive), and definen
is the length of the string. -
While
start < n && s[start] == ' '
, then we keep increasestart
. Now,start
is pointing to the beginning of the word. Then updateend = start + 1
, whileend < n && s[end] != ' '
, then we keep increaseend
. Now,end
is pointing to the ending of the word (exlusive). -
If
res
is empty, we simply updateres
tos[start, end]
. Else, we appends[start, end] + " "
to the beginning of theres
. After updatingres
, we then updatestart = end + 1
. Repeat step 2 and step 3 whilestart < n
. Ifstart
is equal ton
, we need to stop and return the result.
Solution 2
1 |
|