Given an input string, reverse the string word by word.app
For example, Given s = "the sky is blue", return "blue is sky the".ui
思路: 把string以空格爲間隔分隔開存入array, 而後倒着加入stringBuilder而且每一個加入之後後面加空格,最後記的清除最後一個空格。code
public class Solution { public String reverseWords(String s) { if (s == null || s.length() == 0) { return ""; } String[] array = s.split(" "); StringBuilder sb = new StringBuilder(); for (int i = array.length - 1; i >= 0; i--) { if (!array[i].equals("")) { sb.append(array[i]).append(" "); } } //remove the last " " return sb.length() == 0 ? "" : sb.substring(0, sb.length() - 1); } }