Intuition
Splitting on whitespace naturally drops leading, trailing, and repeated spaces and yields the words as a list. Reverse that list and join it back with single spaces.
Explanation
Idea
The messy part of this problem is the spacing — leading, trailing, and multiple internal spaces. Splitting on runs of whitespace cleanly extracts just the words, discarding all the extra spaces. Then reversing the word list and joining with a single space produces the exact required format.
Algorithm
- Split
son whitespace into a list of words (empty tokens dropped). - Reverse the list.
- Join with a single space and return.
Worked example: " the sky is blue "
- Split →
['the', 'sky', 'is', 'blue'](all extra spaces gone). - Reverse →
['blue', 'is', 'sky', 'the']. - Join →
"blue is sky the".
Complexity
- Time: O(n).
- Space: O(n) for the word list and output.
Implementation
class Solution {
public String reverseWords(String s) {
String[] words = s.trim().split("\\s+");
StringBuilder sb = new StringBuilder();
for (int i = words.length - 1; i >= 0; i--) {
sb.append(words[i]);
if (i > 0) {
sb.append(" ");
}
}
return sb.toString();
}
}