-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path22.cpp
40 lines (36 loc) · 1.06 KB
/
22.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
class Solution {
public:
string reverseWords(string s) {
string reverse;
string finall;
int n = s.size();
bool wordstart = false;
for(int i = n-1; i >= 0; i--) {
if(s[i] == ' ' && wordstart == false) {
continue;
}
if(s[i] == ' ' && wordstart == true) {
wordstart = false;
for(int j = reverse.size() - 1; j >= 0; j--) {
finall.push_back(reverse[j]);
}
finall.push_back(' ');
reverse.clear();
continue;
}
wordstart = true;
reverse.push_back(s[i]);
}
// Add the last word to finall
if (!reverse.empty()) {
for (int j = reverse.size() - 1; j >= 0; j--) {
finall.push_back(reverse[j]);
}
}
// Remove the trailing space if it exists
if (!finall.empty() && finall.back() == ' ') {
finall.pop_back();
}
return finall;
}
};