import java.util.*;
public class Solution {
public String ReverseSentence(String str) {
if (str.length() < 2) {
return str;
}
int start = 0;
char pre = str.charAt(0);
Stack<String> stack = new Stack<>();
for (int i = 0; i < str.length(); i++) {
char currentChr = str.charAt(i);
if ((currentChr == ' ' && pre != ' ') || (currentChr != ' ' && pre == ' ')) {
String tmpStr = str.substring(start, i);
stack.push(tmpStr);
pre = currentChr;
start = i;
}
}
stack.push(str.substring(start));
StringBuffer sb = new StringBuffer("");
while (!stack.isEmpty()) {
sb.append(stack.pop());
}
return new String(sb);
}
}