Amazon Interview Question
Software Engineer / DevelopersHere is the working version of the algorithm in C to do word reversals in a string/sentence.
/*
Algorithm..
1. Reverse whole sentence first.
2. Reverse each word individually.
All the reversing happens in-place.
*/
#include <stdio.h>
void rev(char *l, char *r);
int main(int argc, char *argv[])
{
char buf[] = "the world will go on forever";
char *end, *x, *y;
// Reverse the whole sentence first..
for(end=buf; *end; end++);
rev(buf,end-1);
// Now swap each word within sentence...
x = buf-1;
y = buf;
while(x++ < end)
{
if(*x == '\0' || *x == ' ')
{
rev(y,x-1);
y = x+1;
}
}
// Now print the final string....
printf("%s\n",buf);
return(0);
}
// Function to reverse a string in place...
void rev(char *l,char *r)
{
char t;
while(l<r)
{
t = *l;
*l++ = *r;
*r-- = t;
}
}
what the crap,... question is asking to reverse the words of a string not the string itself. like "It is a dog." should be "tI si a god."
One of the most efficient methods is to use a stack for it, push all the characters in the given string from the end position and when there is any space encountered pop all the characters from the stack and concatenate them together along with space at the end to form a string and keep repeating the step until the stack is empty.
Imlementation:
void reversewords(string str){
stack<char> s;
string st = "";
for(int i = str.length() - 1; i >= 0; i--){
if(str[i] == ' '){
while(!s.empty()){
char c = s.top();
s.pop();
st += c;
}
st += str[i];
}
else
s.push(str[i]);
}
while(!s.empty()){
char d = s.top();
s.pop();
st += d;
}
cout<<st<<endl;
}
first reverse the whole string
- ssn October 23, 2008then reverse all the chars in the words alone..
eg., sandman is coming
first step: gnimoc si namdnas
sec step: coming is sandman