L151. Reverse Words in a String

Problem:

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

Example 1:

Input: "the sky is blue"
Output: "blue is sky the"

Example 2:

Input: "  hello world!  "
Output: "world! hello"
Explanation: Your reversed string should not contain leading or trailing spaces.

Solution:

  • The trim() method in java checks this Unicode value before and after the string, if it exists then removes the spaces and returns the omitted string.

public String reverseWord(String str){
    if(str == null || str.length == 0) return null;
    char[] char = str.toCharArray();
    int len = char.length;
    int last = len - 1;
    int start = 0, end = 0, first = 0, i=0;
    while(i < len){
        start = i;
        while(i < len && char[i] = ' '){
            i++;
        }
        first = i;
        while(i < last && char[i] !=' ' && char[i+1] != ' '){
            i++;
        }
        end = i;
        reverseString(char, start, end);
        i = start + (end - first) + 1;
        i++
    }
    reverseString(char, 0 ,last);
    return String.valueOf(chars).trim();
}
private void reverseString(char[] chars, int start, int end){
    if(chars == null || start >= end || end >= chars.length){
        return;
    }
    while(start < end){
        char tmp = chars[start];
        chars[start] = chars[end];
        chars[end] = tmp;
        start++;
        end--;
    }
    
}

Last updated

Was this helpful?