leetcode--Reverse Words in a String

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

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

click to show clarification.

 

public class Solution {
    public String reverseWords(String s) {
        StringBuffer reverse = new StringBuffer();
		int len = s.length();
		if(len > 0){
			int end = 0;
			int start = 0;
			int length = 0;
			while(start < len){
				if(s.charAt(start) == 32){
					++start;
				        ++end;
				}
				else {
					if(end < len && s.charAt(end) != 32)
						++end;
					else{
						reverse.insert(0, " "+ s.substring(start, end));
						start = end;
						length += (end - start + 1);
					}
				}			
			}	
			if(length > 0)
				reverse = reverse.deleteCharAt(0);
		}	
		return reverse.toString();
    }
}

  

posted @ 2014-03-10 11:53  Averill Zheng  阅读(305)  评论(0编辑  收藏  举报