Reverse Words in a String
Given a string s, reverse the order of words. Multiple spaces between words should be reduced to a single space. Leading/trailing spaces should be removed.
Example 1
Input: "the sky is blue" → Output: "blue is sky the"
Example 2
Input: " hello world " → Output: "world hello"
Solution Approach
Split by spaces, filter empty strings, reverse the list, join with single space.
- Use built-in split or manual two-pointer approach.
- Trim the string, split on whitespace (handles multiple spaces).
- Reverse the resulting array.
- Join with single space.
Java
class Solution {
public String reverseWords(String s) {
String[] words = s.trim().split("\\s+");
int lo = 0, hi = words.length - 1;
while (lo < hi) {
String tmp = words[lo]; words[lo] = words[hi]; words[hi] = tmp;
lo++; hi--;
}
return String.join(" ", words);
}
}
- Time Complexity: O(N)
- Space Complexity: O(N)