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

整体不是很难。里面java自带的spilt函数就可以将字符串分开。不过在过程中还是未考虑到一些特殊的情况。

比如:输入为类似“  a    b  ”,开头或者中间有多于一个空格的情况,这样的话分割后的数组中会多空格。

具体解法如下:


public class Solution {
      public String reverseWords(String s) {
        s = s.trim();
       if(s.equals("") || s.equals(null))
       {
           return s;
       }
       String[] words = s.split(" ");
       String reverse = "";
       int length = words.length;
       for(int i=length-1;i>0;i--)
       {
           if(!words[i].equals(""))
           {
               reverse = reverse + words[i] + " ";
           }
       }
       reverse = reverse + words[0];
       return reverse;
    }
}

posted on 2014-05-06 12:01  JessiaDing  阅读(113)  评论(0编辑  收藏  举报