-
Notifications
You must be signed in to change notification settings - Fork 0
/
151. Reverse Words in a String
66 lines (50 loc) · 1.04 KB
/
151. Reverse Words in a String
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
55
56
57
58
59
60
61
62
63
64
65
66
class Solution {
public:
void reverseS(string &s, int i, int j){
while(i<j)
{
swap(s[i], s[j]);
i++;
j--;
}
}
string reverseWords(string s)
{
string st;
reverse(s.begin(), s.end());
int l = 0;
//remove extra spaces
bool extra = false;
for(int i=0; i<s.length(); i++)
{
if(s[i] == ' ')
{
if(extra == false)
{
continue;
}
else
st+=s[i];
extra = false;
}
else
{
st += s[i];
extra = true;
}
}
//reversing all the words when we get a space
for(int i=0; i<st.length(); i++)
{
if(st[i] == ' ')
{
reverseS(st, l, i-1);
l = i+1;
}
}
reverseS(st, l, st.length()-1);
if(st[st.length() -1] == ' ')
st.pop_back();
return st;
}
};