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".

Clarification
  • What constitutes a word?
    A sequence of non-space characters constitutes a word.
  • Could the input string contain leading or trailing spaces?
    Yes. However, your reversed string should not contain leading or trailing spaces.
  • How about multiple spaces between two words?
    Reduce them to a single space in the reversed string.

思路:采用String 的 split 方法进行分割 , 其分割的正则表达式为" ".

 1 public class Solution {
 2     public String reverseWords(String s) {
 3         if (s == null) {
 4             return null;
 5         }
 6         s = s.trim();
 7         if (s.length() == 0) {
 8             return "";
 9         }
10         String[] str = s.split(" ");
11         StringBuilder sb = new StringBuilder();
12         for (int i = str.length - 1; i >= 0; i--) {
13             if (!str[i].equals(""))
14             sb.append(str[i]).append(" ");
15         }
16         return sb.length() == 0 ? "" : sb.substring(0, sb.length() - 1);
17     }
18 }

 

 

posted @ 2016-06-02 22:07  YuriFLAG  阅读(117)  评论(0)    收藏  举报