-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathReverse words in a string-Leetcode-AnujSoni.cpp
54 lines (49 loc) · 1.22 KB
/
Reverse words in a string-Leetcode-AnujSoni.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
51
52
53
54
class Solution {
public:
void trim(string& s){
int i=0;
while(s[i]==' ')
i++;
s = s.substr(i);
reverse(s.begin(),s.end());
i=0;
while(s[i]==' ')
i++;
s = s.substr(i);
reverse(s.begin(),s.end());
}
string reverseWords(string s) {
ios_base::sync_with_stdio(NULL);
cin.tie(NULL);
cout.tie(NULL);
if(s.length() == 0)
return s;
int flag = 0;
for(int i=0;i<s.length();i++)
if(s[i] != ' ')
flag = 1;
if(flag == 0)
return "";
trim(s);
vector<string> v;
string m="";
for(int i=0;i<s.length();i++){
if(s[i] == ' ' && s[i] == s[i-1])
continue;
m += s[i];
}
s = m;
stringstream temp(s);
string intermediate;
while(getline(temp,intermediate,' '))
v.push_back(intermediate);
reverse(v.begin(),v.end());
string res;
for(int i=0;i<v.size();i++){
res+=v[i];
res.push_back(' ');
}
res.pop_back();
return res;
}
};