151. 反转字符串中的单词
为保证权益,题目请参考 151. 反转字符串中的单词(From LeetCode).
解决方案1
CPP
C++
//
// Created by lenovo on 2020/4/10.
//
/*
* LeetCode 151
*/
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Solution {
public:
string reverseWords(string s) {
if (s.empty()){
return "";
}
vector<string> res;
enum STATE{
start, chars
} state;
state = start;
string tmp;
for(char ch:s){
if(state == start){
if(ch != ' '){
tmp = tmp + ch;
state = chars;
}
}else if (state == chars){
if(ch != ' '){
tmp = tmp + ch;
}else{
res.push_back(tmp);
tmp.clear();
state = start;
}
}
}
if (!tmp.empty()){
res.push_back(tmp);
}
string ans;
for(auto iter = res.rbegin(); iter !=res.rend();){
ans += *iter;
iter ++;
if (iter == res.rend()){
break;
}else{
ans += " ";
}
}
return ans;
}
};
int main()
{
Solution so;
cout << so.reverseWords(" ");
return 0;
}
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69