-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path151.reverse-words-in-a-string.cpp
50 lines (45 loc) · 1.04 KB
/
151.reverse-words-in-a-string.cpp
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
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
/*
* @lc app=leetcode id=151 lang=cpp
*
* [151] Reverse Words in a String
*/
// @lc code=start
class Solution {
public:
string reverseWords(string s) {
int slow = 0, fast = 0;
reverse(s.begin(), s.end());
while (fast < s.size()) {
if (fast == 0 && s[fast] == ' ' || (s[fast] == ' ' && s[fast - 1] == ' ')) {
fast++;
continue;
}
s[slow] = s[fast];
slow++;
fast++;
}
s.resize(slow);
while (s.back() == ' ') {
s.pop_back();
}
for (slow = 0, fast = 0; fast < (int)s.size(); ) {
while (s[fast] != ' ' && fast < s.size()) {
fast++;
};
reverse(s.begin() + slow, s.begin() + fast);
fast++;
slow = fast;
}
return s;
}
};
// @lc code=end
int main() {
Solution S1;
cout << S1.reverseWords(" a ");
return 0;
}