Reverse Words in a String

Given an input string, reverse the string word by word.

For example,
Given s = "the sky is blue",
return "blue is sky the".

先要去除首尾两端的空格。 中间可能有多个连续空格, 所以split的时候要用regex。 eg: "    a     b     "

 1 public class Solution {
 2     public String reverseWords(String s) {
 3         String t = s.trim();
 4         String[] pieces = t.split("[ ]+");
 5         int size = pieces.length;
 6         if(size == 0) return t;
 7         StringBuilder sb = new StringBuilder();
 8         for(int i = 0; i < size - 1; i ++){
 9             sb.append(pieces[size - 1 - i]);
10             sb.append(" ");
11         }
12         sb.append(pieces[0]);
13         return sb.toString();
14     }
15 }
原文地址:https://www.cnblogs.com/reynold-lei/p/3771660.html