LeetCode-151-Reverse Words in s 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.

解题思路:先逐词翻转,再整句翻转。注意去除空格。

void reverseWords(string &s, int i, int j){
    while(i < j){
        char temp = s[i];
        s[i++]=s[j];
        s[j--]=temp;        
    }   
}

void reverseWords(string &s){
    int i = 0;
    int j = 0;
    int l = 0;
    int n = s.size();
    int count = 0;
    while(true){
        while(i < n && s[i] == ' ') i++;
        if(i==n) break;
        if(count) s[j++] = ' ';
        l=j;
        while(i < n && s[i]!= ' ') {s[j]=s[i]; j++; i++;}
        reverseWords(s,l,j-1);
        count++;
    }
    s.resize(j);
    reverseWords(s,0,j-1);
}

 

上一篇:霸榜GitHub必读书籍:编写高质量代码改善Java程序员的151个建议


下一篇:151. Reverse Words in a String