151. Reverse Words in a String

Description

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

Note:

  • A word is defined as a sequence of non-space characters.

  • Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces.

  • You need to reduce multiple spaces between two words to a single space in the reversed string.

Constraints

Approach

Examples

Input: "the sky is blue"

Output: "blue is sky the"

Solutions

/**
 * Time complexity : 
 * Space complexity : 
 */

class Solution {
    public String reverseWords(String s) {
        int i = s.length()-1;
        StringBuilder result = new StringBuilder();
        while(i >= 0) {
            while(i >= 0 && s.charAt(i) == ' ') {
                i--;
            }
            String tmp = "";
            while(i >= 0 && s.charAt(i) != ' ') {
                tmp = s.charAt(i) + tmp;
                i--;
            }
            if(tmp.length() > 0) {
                result.append(" ").append(tmp);
            }
        }
        if(result.length() == 0) {
            return result.toString();
        }
        return result.substring(1);
    }
}

Follow up

Last updated

Was this helpful?