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

click to show clarification.

Clarification: What constitutes a word?

A sequence of non-space characters constitutes a word.

Could the input string contain leading or trailing spaces?

Yes. However, your reversed string should not contain leading or trailing spaces.

How about multiple spaces between two words?

Reduce them to a single space in the reversed string.

public class Solution {
    public String reverseWords(String s) {
        StringBuilder sb = new StringBuilder();
        for(int i= s.length()-1; i>=0; i--){
            while(i>=0 && s.charAt(i) == ' ') i--;
            if(i < 0) break;
            /* if sb is empty, which means it is first word met, simple skip, and if it is not, when we reach here, the string is not done processing, so append a space.
            if(sb.length() != 0) sb.append(' ');
            StringBuilder w = new StringBuilder();
            /* Add the string in reverse order. */
            while(i>=0 && s.charAt(i) != ' ') w.append(s.charAt(i--));

        return sb.toString();

results matching ""

    No results matching ""