forked from HemangTheHuman/hacktoberfest-2022
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseWordsInString.cpp
More file actions
40 lines (38 loc) · 851 Bytes
/
ReverseWordsInString.cpp
File metadata and controls
40 lines (38 loc) · 851 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
// Given a string s, reverse the words of the string.
// Example 1:
// Input: s=”this is an amazing program”
// Output: “program amazing an is this”
// Example 2:
// Input: s=”This is decent”
// Output: “decent is This”
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s="Words to reverse";
cout<<"Before reversing words: "<<endl;
cout<<s<<endl;
s+=" ";
stack<string> st;
int i;
string str="";
for(i=0;i<s.length();i++)
{
if(s[i]==' ')
{
st.push(str);
str="";
}
else str+=s[i];
}
string ans="";
while(st.size()!=1)
{
ans+=st.top()+" ";
st.pop();
}
ans+=st.top();// The last word should'nt have a space after it
cout<<"After reversing words: "<<endl;
cout<<ans;
return 0;
}