Using a Stack
Uses O(n) memory and time.
public class Solution {
public String reverseWords(String s) {
s = s.trim();
Stack<String> track = new Stack<String>();
String word = "";
int i=0;
while (i < s.length()) {
if (s.charAt(i) == ' ') {
track.push(word);
word = "";
while(i<s.length() && s.charAt(i) == ' ')
i++;
continue;
}
word +=s.charAt(i++);
}
if (word != "") {
track.push(word);
}
s = "";
while(!track.isEmpty()) {
s+= track.pop()+" ";
}
return s.trim();
}
}