Reverse the order of words in a string (trim leading/trailing spaces, single space between words).
Input: s="the sky is blue" → Output: "blue is sky the"
Input: s=" hello world " → Output: "world hello"
Split by whitespace, filter empty, reverse array, join with single space.
- Split string by spaces
- Filter out empty tokens
- Reverse the array
- Join with single space
public String reverseWords(String s) {
String[] words = s.trim().split("\s+");
int left = 0, right = words.length - 1;
while (left < right) {
String tmp = words[left]; words[left] = words[right]; words[right] = tmp;
left++; right--;
}
return String.join(" ", words);
}
- Time Complexity: O(n)
- Space Complexity: O(n)