-
-
Notifications
You must be signed in to change notification settings - Fork 300
/
186.cpp
36 lines (36 loc) · 1.17 KB
/
186.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
__________________________________________________________________________________________________
class Solution {
public:
void reverseWords(vector<char>& str) {
int left = 0, n = str.size();
for (int i = 0; i <= n; ++i) {
if (i == n || str[i] == ' ') {
reverse(str, left, i - 1);
left = i + 1;
}
}
reverse(str, 0, n - 1);
}
void reverse(vector<char>& str, int left, int right) {
while (left < right) {
char t = str[left];
str[left] = str[right];
str[right] = t;
++left; --right;
}
}
};
__________________________________________________________________________________________________
class Solution {
public:
void reverseWords(vector<char>& str) {
reverse(str.begin(), str.end());
for (int i = 0, j = 0; i < str.size(); i = j + 1) {
for (j = i; j < str.size(); ++j) {
if (str[j] == ' ') break;
}
reverse(str.begin() + i, str.begin() + j);
}
}
};
__________________________________________________________________________________________________