-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathReverse-Words-in-a-string.cc
54 lines (51 loc) · 1.43 KB
/
Reverse-Words-in-a-string.cc
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
class Solution {
public:
void reverseWords(string &s) {
if(s.empty()) return;
string res, word;
for(auto x : s) {
if(x == ' ') {
if(!word.empty()) {
reverse(word.begin(), word.end());
res += word + ' ';
word.clear();
}
continue;
}
word.push_back(x);
}
if(!word.empty()) { //do not forget
reverse(word.begin(), word.end());
res += word + ' ';
}
if(!res.empty()) res.pop_back();
reverse(res.begin(), res.end());
res.swap(s);
}
};
class Solution {
public:
void reverseWords(string &s) {
if(s.empty()) return;
//reverse the whose string first
reverse(s.begin(), s.end());
//reverse each words separately
for(int i=0; i<s.size(); ++i) {
if(s[i] == ' ') continue;
assert(s[i] != ' ');
int j=i;
while(j < s.size() && s[j] != ' ') ++j;
reverse(s.begin()+i, s.begin()+j);
i = j;
}
//remove extra spaces
int trail = s.size()-1;
while(trail >=0 && s[trail] == ' ') --trail;
int i(0), p(0);
for(; i<=trail; ++i) {
if(s[i] != ' ' || (p > 0 && s[p-1] != ' '))
s[p++] = s[i];
}
s = s.substr(0, p);
}
};