Given an input string, reverse the string word by word.
For example,
Given s = "the sky is blue
",
return "blue is sky the
".
public class Solution { public String reverseWords(String s) { if(s.length() == 0) return s; s += " "; Stack<String> stack = new Stack<String>(); StringBuilder temp = new StringBuilder(); for(int i = 0 ; i < s.length() ; i++){ if(s.charAt(i) ==' ' ){ if(temp.length() > 0) stack.push(temp.toString()); temp = new StringBuilder(); } else{ temp.append(s.charAt(i)); } } StringBuilder result = new StringBuilder(); if(stack.isEmpty()) return ""; while(!stack.isEmpty()){ result.append(stack.pop()); if(!stack.isEmpty()) result.append(" "); } return result.toString(); } }