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”.

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

Solution:

public class Solution {
    public String reverseWords(String s) {
        String ans = "";
        for(int i=s.length()-1; i>=0; i--){
            while(i>=0 && s.charAt(i)==' ') i--;
            if(i>=0){
                int j=i;
                while(j>=0 && s.charAt(j)!=' ') j--;
                String word = s.substring(j+1, i+1);
                if(ans.length()==0){
                    ans = word;
                } else {
                    ans = ans + " " + word;
                }
                i = j;
            }
        }
        return ans;
    }
}
comments powered by Disqus