186. Reverse Words in a String II - Medium

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

Example:

Input:  ["t","h","e"," ","s","k","y"," ","i","s"," ","b","l","u","e"]
Output: ["b","l","u","e"," ","i","s"," ","s","k","y"," ","t","h","e"]

Note: 

  • A word is defined as a sequence of non-space characters.
  • The input string does not contain leading or trailing spaces.
  • The words are always separated by a single space.

Follow up: Could you do it in-place without allocating extra space?

 

two pointers

time: O(n), space: O(1)

class Solution {
    public void reverseWords(char[] s) {
        reverse(s, 0, s.length - 1);
        int i = 0, j = 0;
        while(j < s.length) {
            if(s[j] == ' ') {
                reverse(s, i, j - 1);
                j++;
                i = j;
            } else {
                j++;
            }
        }
        reverse(s, i, j - 1);
    }
    
    private void reverse(char[] c, int i, int j) {
        while(i < j) {
            char tmp = c[i];
            c[i] = c[j];
            c[j] = tmp;
            i++;
            j--;
        }
    }
}

 

posted @ 2019-08-12 15:20  fatttcat  阅读(133)  评论(0编辑  收藏  举报