码迷,mamicode.com
首页 > 编程语言 > 详细

leetcode 151. Reverse Words in a String --------- java

时间:2016-11-19 01:16:15      阅读:240      评论:0      收藏:0      [点我收藏+]

标签:ring   for   sub   pac   length   bsp   etc   buffer   tostring   

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.

 

倒序字符串。

 

注意使用BufferString,因为如果使用String的话,会多次建立对象,会很慢。

public class Solution {
    public String reverseWords(String s) {
        int len = s.length();
        if( len == 0)
            return s;
        StringBuffer result = new StringBuffer() ;
        int end = len-1,start = 0;
        while( end >= 0 && s.charAt(end) == ‘ ‘)
            end--;
        if( end == -1)
            return result.toString();
        while( start < len && s.charAt(start) == ‘ ‘)
            start++;
        int pos = end+1;
        for( int i = end ; i >= start ; i-- ){
            if( s.charAt(i) == ‘ ‘) {
                result.append(s.substring(i+1,pos));
                result.append(" ");
                while (i < end && s.charAt(i) == ‘ ‘)
                    i--;
                i++;
                pos = i;

            }
        }
        result.append(s.substring(start,pos));
        return result.toString();
    }
}

 

leetcode 151. Reverse Words in a String --------- java

标签:ring   for   sub   pac   length   bsp   etc   buffer   tostring   

原文地址:http://www.cnblogs.com/xiaoba1203/p/6079249.html

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