Reverse words in a sentence

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

3 comments:

Unknown said...

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

Unknown said...

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

Anonymous said...

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);
}
}

 
Stats