LeetCode: 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”.

My codes:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <iostream>
#include <list>
#include <string>

using namespace std;

class Solution {
public:
    void reverseWords(string &s) {
      string word;
      list<string> tokens;
      for (string::const_iterator it = s.begin(); it != s.end(); ++it) {
        const char c = *it;
        if (c == ' ') {
          if (word.empty()) {
            continue;
          } else {
            tokens.push_front(word);
            word.clear();
          }
        } else {
          word.append(1, c);
        }
      }
     
      if (!word.empty()) {
        tokens.push_front(word);
      }
     
      s.clear();
      bool is_first = true;
      for (list<string>::const_iterator it = tokens.begin(); it != tokens.end(); ++it) {
        if (is_first) {
          is_first = false;
        } else {
          s.append(1, ' ');
        }
        s.append(*it);
      }
    }
};

int main(int argc, const char* argv[]) {
  Solution sl;
  string s(" the sky   is blue  ");
  cout << s << endl;
  sl.reverseWords(s);
  cout << "'" << s << "'" << endl;
}

Leave a Comment