Reverse Words In A String
If the given input string is " Welcome to Coding Ninjas", then you should return "Ninjas Coding to Welcome" as the reversed string has only a single space between two words and there is no leading or trailing space.
The first line of input contains a single integer T, representing the number of test cases or queries to be run.
Then the T test cases follow.
The first and only one of each test case contains a string that you need to reverse word by word.
For every test case, print the reversed string such that there should be only one space between two strings and there should not be any trailing space.
Do not print anything. It has already been taken care of.
If the string data type is immutable in your language, consider using a mutable data type as an alternative.
If the string data type is mutable in your language, can you solve it in place with O(1) extra space?
1 <= T <= 50
0 <= N <= 10^5
Time Limit: 1 sec
2
Welcome to Coding Ninjas
I am a star
Ninjas Coding to Welcome
star a am I
In the first test case, you need to reduce multiple spaces between two words to a single space in the reversed string and observe how the multiple spaces, leading and trailing spaces have been removed.
In the second test case, Your reversed string should not contain leading or trailing spaces.
1
Hello World!!
World!! Hello
#includ<bits/stdc++.h>string reverseString(string str){ // Write your code here. int j=0; for(int i=0;i<str.size();i++){ if(str[i]==' '){ reverse(str.begin()+j,str.begin()+i); i++; j=i; } else continue; } reverse(str.begin(),str.end());
return str;}
Comments
Post a Comment