Reverse Words in a String

来源:互联网 发布:淘宝win7 激活靠谱不 编辑:程序博客网 时间:2024/06/08 09:40

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

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

java

public class Solution {
    public String reverseWords(String s) {
         
        int start=0;
        int end=s.length()-1;
        while(start<=s.length()-1&&s.charAt(start)==' '){
            start++;
        }
        while(end>=0&&s.charAt(end)==' '){
            end--;
        }
        if(start>end) return "";
        StringBuffer result= new StringBuffer();
        while(start<=end){
        StringBuffer word=new StringBuffer();
        while(end>=start&&s.charAt(end)!=' '){
        word.append(s.charAt(end));end--;
        }
        word.reverse();
        if(!word.equals("")) {result.append(word+" ");}
        while(end>=start&&s.charAt(end)==' ') end--;}
        return result.substring(0,result.length()-1).toString();
    }
}

0 0