Reverse Word Wise
Reverse the given string word wise. That is, the last word in given string should come at 1st place, last second word at 2nd place and so on. Individual words should remain as it is.
Input format :
String in a single line
Output format :
Word wise reversed string in a single line
Constraints :
0 <= |S| <= 10^7
where |S| represents the length of string, S.
Sample Input 1:
Welcome to Coding Ninjas
Sample Output 1:
Ninjas Coding to Welcome
Sample Input 2:
Always indent your code
Sample Output 2:
code your indent Always
Source Code :
int length(char input[])
{
int len = 0;
int i = 0;
while(input[i] != '\0')
{
len++;
i++;
}
return len;
}
void reverseWholeString(char input[])
{
int len = length(input);
int i = 0;
int ei = len -1;
while(i<len/2)
{
int temp;
temp = input[ei];
input[ei] = input[i];
input[i] = temp;
i++;
ei--;
}
input[len] ='\0';
}
void reverseEachWord(char input[],int si,int ei){
int i =0 ;
//cout<<"ayush"<<endl;
int l = (ei+1-si)/2;
while(i<l)
{
int temp = input[ei];
input[ei] = input[si];
input[si] = temp;
si++;
ei--;
i++;
}
}
void reverseStringWordWise(char input[]) {
// Write your code here
reverseWholeString(input);
int j=0,l=0;
int len = length(input);
while(j<len)
{
int si = j;
while(input[j]!= ' '&& input[j]!= '\0')
{
l++;
j++;
}
int ei = l-1;
if(input[j]==' ')
j++;
reverseEachWord(input,si,ei);
l++;
}
}
1 Comments
nice explanation
ReplyDelete