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

Reverse Words in a String

时间:2015-06-16 06:39:10      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:

话说我们昨晚去看了侏罗纪公园,原来xd就是我最爱的巨幕,来美国这么多年了,怀念和小星星一路成长,一路看电影的经历,avatar是我们在美国一起看的第一部电影。老美看完好片子,还喜欢鼓个掌。

 

这题one pass in place就是麻烦,要多做个string来判断单词

要用到sb的insert,不过可以练习一下关于corner case的理解

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

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

Update (2015-02-12):
For C programmers: Try to solve it in-place in O(1) space.

click to show clarification.

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.
public class Solution {
    public String reverseWords(String s) {
        s = s.trim();
        if(s==null ||s.length()<=1) return s;
        StringBuilder sb  = new StringBuilder();
        for(int i = 0;i<s.length();i++){
            if(s.charAt(i)!=‘ ‘){
                String word = new String();
                while(i<s.length() && s.charAt(i)!=‘ ‘){
                    word = "" + word +  s.charAt(i);
                    i++;
                }
                if(sb.length()!=0){
                    sb.insert(0," ");
                }
                    sb.insert(0,word);
            }
        }
            
           
        return sb.toString();
    }
}

 

Reverse Words in a String

标签:

原文地址:http://www.cnblogs.com/jiajiaxingxing/p/4579630.html

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