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
replaceAllto replace more than one space into one space, thensplitby 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
startandendpoint to a word’s beginning index and end index (exclusive), and definenis the length of the string. -
While
start < n && s[start] == ' ', then we keep increasestart. Now,startis pointing to the beginning of the word. Then updateend = start + 1, whileend < n && s[end] != ' ', then we keep increaseend. Now,endis pointing to the ending of the word (exlusive). -
If
resis empty, we simply updaterestos[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. Ifstartis equal ton, we need to stop and return the result.
Solution 2
1 | |