码迷,mamicode.com
首页 > 其他好文 > 详细

Reverse Words in a String

时间:2016-06-02 23:39:36      阅读:269      评论:0      收藏:0      [点我收藏+]

标签:

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     /**
 3      * @param s : A string
 4      * @return : A string
 5      */
 6     public String reverseWords(String s) {
 7         if(s == null || s.length() == 0) {
 8             return "";
 9         }
10         String[] words = s.split(" ");
11         StringBuilder builder = new StringBuilder();
12         for (int i = words.length - 1; i >= 0; i--) {
13             if (words[i] != " ") {
14                 builder.append(words[i]).append(" ");
15             }
16         }
17         return builder.length() == 0 ? "":builder.substring(0, builder.length() - 1);
18     }
19 }

 

Reverse Words in a String

标签:

原文地址:http://www.cnblogs.com/FLAGyuri/p/5554577.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!