-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlt21.cpp
36 lines (34 loc) · 961 Bytes
/
lt21.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:
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]);
}
if (!reverse.empty()) {
for (int j = reverse.size() - 1; j >= 0; j--) {
finall.push_back(reverse[j]);
}
}
if(!finall.empty() && finall.back()==' '){
finall.pop_back();
}
return finall;
}
};