leetcode 151. Reverse Words in a String

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

Example:  

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

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.

Follow up: For C programmers, try to solve it in-place in O(1) space.

 

先把整个数组reverse一下再逐个reverse单词。

具体采用two pointer 和 swap 的方法来reverse。

public class Solution {
    public String reverseWords(String s) {
        if(s == null) return null;
        char[] a = s.toCharArray();
        int n = s.length();
        //reverse the whole string
        reverse(a, 0, n-1);
        //reverse every word
        reverseWords(a, n);
        //clean up spaces
        return cleanSpaces(a, n);
    }
    public void reverseWords(char[] a, int n) {
        int i = 0, j = 0;
        while(i < n) {
            while(i < j || i < n && a[i] == ' ') i++; //skip spaces
            while(j < i || j < n && a[j] != ' ') j++; //skip non spaces
            reverse(a, i, j-1);
        }
    }
    
    public String cleanSpaces(char[] a, int n){
        int i = 0, j = 0;
        while(j < n) {
            while(j < n && a[j] == ' ') j++; //skip spaces
            while(j < n && a[j] != ' ') a[i++] = a[j++]; // keep non spaces
            while(j < n && a[j] == ' ') j++; //skip spaces
            if(j < n) a[i++] = ' ';    
        }
        return new String(a).substring(0, i);
    }
    private void reverse(char[] a, int i, int j) {
        while(i < j) {
            char t = a[i];
            a[i++] = a[j];
            a[j--] = t;
        }
    }
    
    
}

 

posted @ 2019-02-26 19:58  JamieLiu  阅读(131)  评论(0编辑  收藏  举报