File tree Expand file tree Collapse file tree 1 file changed +53
-0
lines changed Expand file tree Collapse file tree 1 file changed +53
-0
lines changed Original file line number Diff line number Diff line change
1
+ ```
2
+ #include <iostream>
3
+ #include <string>
4
+ #include <sstream>
5
+ #include <stack>
6
+ using namespace std;
7
+
8
+ //using stack space O(n)
9
+ class Solution {
10
+ public:
11
+ void reverseWords(string &s) {
12
+ if (s.empty()) return;
13
+ stack<string> st;
14
+ for (int i = 0; i < s.size(); ++i) {
15
+ string sub;
16
+ while (s[i] != ' ' && i < s.size()) {
17
+ sub.push_back(s[i++]);
18
+ }
19
+ if (!sub.empty()) st.push(sub);//空字符串因为有‘\0’的存在也会被当做一个元素放到stack中
20
+ }
21
+ string res;
22
+ while (!st.empty()) {
23
+ res += st.top();
24
+ res += " ";
25
+ st.pop();
26
+ }
27
+ if (!res.empty()) res.pop_back();
28
+ s = res;
29
+ }
30
+ };
31
+
32
+ class Solution2 {
33
+ public:
34
+ void reverseWords(string &s) {
35
+ istringstream is(s);
36
+ is >> s;
37
+ cout << s.size();
38
+ string tmp;
39
+ while (is >> tmp) s = tmp + " " + s;
40
+ // if (!s.empty() && s[0] == ' ') s = "";
41
+ }
42
+ };
43
+ int main() {
44
+ Solution3 s;
45
+ // string str{"The sky is blue"};
46
+ // string str{" "};
47
+ string str{" The sky is blue"};
48
+ // string str{"The sky is blue "};
49
+ // string str{"The sky is blue"};
50
+ s.reverseWords(str);
51
+ cout << str << "*";
52
+ }
53
+ ```
You can’t perform that action at this time.
0 commit comments