This repository has been archived by the owner on May 29, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 796
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
chore(CPlusPlus): add reverse the string wordwise (#1100)
- Loading branch information
1 parent
e60d299
commit 6620f32
Showing
2 changed files
with
49 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
// Description :- Given a string, the task is to reverse the order of the words in the given string. | ||
// Example :- | ||
// Input 1: | ||
// A = "the sky is blue" | ||
// Input 2: | ||
// A = "this is ib" | ||
// Output 1: | ||
// "blue is sky the" | ||
// Output 2: | ||
// "ib is this" | ||
|
||
|
||
// Time Complexity = O(N), Space Complexity = O(N) | ||
|
||
#include<bits/stdc++.h> | ||
using namespace std; | ||
|
||
string solve(string s) { | ||
vector<string>v; | ||
string str=""; | ||
for(int i=0;i<s.length();i++){ | ||
if(s[i]!=' '){ | ||
str+=s[i]; | ||
} | ||
else if(str!="" && s[i]==' '){ | ||
v.push_back(str); | ||
str=""; | ||
} | ||
} | ||
if(str!=""){ | ||
v.push_back(str); | ||
} | ||
str=""; | ||
for(int i=v.size()-1;i>0;i--){ | ||
str+=v[i]; | ||
str+=' '; | ||
} | ||
str+=v[0]; | ||
return str; | ||
} | ||
|
||
int main() | ||
{ | ||
string s; | ||
getline(cin, s); | ||
cout<<solve(s); | ||
return 0; | ||
} |