forked from amanss00/ForNewbies
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseWords.cpp
More file actions
41 lines (35 loc) · 734 Bytes
/
ReverseWords.cpp
File metadata and controls
41 lines (35 loc) · 734 Bytes
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
#include <bits/stdc++.h>
using namespace std;
string reverse_words(string &s)
{
int left = 0, i = 0, n = s.size();
while (s[i] == ' ')
i++;
left = i;
while (i < n)
{
if (i + 1 == n || s[i] == ' ')
{
int j = i - 1;
if (i + 1 == n)
j++;
while (left < j)
swap(s[left++], s[j--]);
left = i + 1;
}
if (i > left && s[left] == ' ')
left = i;
i++;
}
reverse(s.begin(), s.end());
return s;
}
int main()
{
string str;
cout << "Enter the String to be reversed : " << endl;
getline(cin, str);
str = reverse_words(str);
cout << str;
return 0;
}