classSolution {publicStringreverseWords(String s) {String[] words =s.trim().split("\\s+");int end =words.length-1;StringBuffer result =newStringBuffer(words[end]);for (int i = end -1; i >=0; i--) {result.append(" "+ words[i]); }returnresult.toString(); }}
Solution 2 (Java)
classSolution {publicStringreverseWords(String s) {if (s ==null||s.length() ==0) {return""; }String[] words =s.split(" ");StringBuffer sb =newStringBuffer();for (int i =words.length-1; i >=0; i--) {if (words[i].equals("")) {continue; }if (sb.length() >0) {sb.append(" "); }sb.append(words[i]); }returnsb.toString(); }}