151. Reverse Words in a String

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

For example, Given s = "the sky is blue", return "blue is sky the".

Clarification:

What constitutes a word?

A sequence of non-space characters constitutes a word.

Could the input string contain leading or trailing spaces?

Yes. However, your reversed string should not contain leading or trailing spaces.

How about multiple spaces between two words?

Reduce them to a single space in the reversed string.

S1: stich backward by word, need O(n) space

S2: two reverse

  1. 去掉多余的空格
  2. reverse整个string
  3. reverse by word 其中二三可以互换。
    class Solution {
    public:
     void reverseWords(string &s) {
         compress(s);
         reverse(s.begin(), s.end());
         reverse_by_word(s);
     }
     void compress(string &s){
         int w = 0;
         for(int r = 0; r < s.size(); ++r){
             if(s[r] != ' '){
                 if(r > 1 && w > 0 && s[r-1] == ' ') s[w++] = ' ';
                 s[w++] = s[r];
             }
         }
         s.resize(w);
     }
     void reverse_by_word(string &s){
         for(int i = 0; i < s.size(); ++i){
             int j = i+1;
             while(j < s.size() && s[j] != ' ') j++;
             reverse(s.begin()+i, s.begin()+j);
             i = j;
         }
     }
    };
    

    186. Reverse Words in a String II

和上题一样

results matching ""

    No results matching ""