Given an array of characters, reverse the words in the sentence.
For example, if the sentence is "Reverse these words", then the output should be "words these reverse".
Source : this interview q
Subscribe to:
Post Comments (Atom)
"Gebo" means to "give and take". This is my attempt to share the knowledge & experience with the community. Focus on Puzzles, Algorithms, Problem Solving, Java & other Technical Discussions.
Buttons reused from http://www.webfruits.it/freebies.htm and http://mysocialbuttons.com/ |
3 comments:
Approach :
1.> If the output is to be "printed" only, then this would work :
Init : Start from the end of the array. Let this index pointer be 'i'. Also set 'end' to 'array.length - 1'
Loop :
- Decrement 'i' until a array[i] is a space.
- Print characters from array[i] to array[end] and then a space
- Set end to i and repeat, till end = 0
Another, non intrusive, really smart answer is on Inder's blog here :
http://inder-gnu.blogspot.com/2007/03/reverse-words-of-string-in-o1-space.html
void reverseF(char ch[], int start, int end)
{
while(start<=end)
swap(ch[start++], ch[end--]);
}
void function(char ch[], int len)
{
reverseF(ch, 0, len-1); //reverse complete string
int start = 0, end = 0; // now reverse word by word
int i = 0;
for(;i<len;)
{
start = i;
while(ch[i] != ' ')
{
i++;
if(ch[i] == '\0')
break;
}
end = i-1;
while(ch[i] == ' ')
i++;
reverseF(ch, start, end);
}
}
Post a Comment