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

Posted xiaoba1203

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 151. Reverse Words in a String --------- java相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode-151-Reverse Words in s String

LeetCode151. Reverse Words in a String

刷题-LeetCode151 Reverse Words in a String

Leetcode 151. Reverse Words in a String 解题报告

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

leetcode-151-reverse word in a string