[Leetcode] reverse words in a string 反转单词

来源:互联网 发布:js对象概念 编辑:程序博客网 时间:2024/05/17 04:30

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

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

return "blue is sky the".

思路:

(1)首先去掉首尾的White Space等字符,利用Java  String 的trim函数
(2)通过空格分割字符串,split(“\\s+”),通过正则匹配两单词间的多个空格。
(3)StringBuffer 添加倒序遍历的Split完后的数组。

 public String reverseWords(String s) {            StringBuffer sb = new StringBuffer();            s =s.trim();            String []ary = s.split("\\s+");            if(s.length()==0) return "";            for(int i = ary.length;i>0;i--){                  if(!ary[i-1].equals(" ")&&i==ary.length)sb.append(ary[i-1]);                  else if(!ary[i-1].equals(" ")&&i!=ary.length) sb.append(" "+ary[i-1]);              }              return sb.toString();      }






0 0