2.27 Reverse words in a string

Description

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.

Method

trim() to delete heading and tailing whitespaces reverse all string and then two pointers to reverse each word

Time and Space Complexity

o(n) o(n)

Code

public class Solution { public String reverseWords(String s) { if (s == null || s.trim().length() <= 1){ return s.trim(); }

       char[] strs = s.trim().toCharArray();

       reverse(strs, 0, strs.length - 1);

       StringBuilder sb = new StringBuilder();
       int i = 0;
       while (i < strs.length){
            while (i < strs.length && strs[i] == ' '){
                   i++;
            }
            if (i >= strs.length){
                break;
            }
            int j = i;
            while (j < strs.length && strs[j] != ' '){
                     j++;
            }

            reverse(strs, i, j - 1);
            sb.append(strs, i, j - i).append(" ");
            i = j + 1;
       }
       return sb.deleteCharAt(sb.length() - 1).toString();
       }


private void reverse(char[] strs, int l, int r){
        while (l < r){
               char c = strs[l];
               strs[l] = strs[r];
               strs[r] = c;
               l++;
               r--;
        }
}

results matching ""

    No results matching ""