I have this string s1 = "My name is X Y Z"
and I want to reverse the order of the words so that s1 = "Z Y X is name My"
.
I can do it using an additional array. I thought hard but is it possible to do it inplace (without using additional data structures) and with the time complexity being O(n)?
How about ...
I guess that's not in-line tho.
Reverse the entire string, then reverse the letters of each individual word.
After the first pass the string will be
and after the second pass it will be
It can be done more simple using sscanf:
Better version
Check my blog http://bamaracoulibaly.blogspot.co.uk/2012/04/19-reverse-order-of-words-in-text.html
We can insert the string in a stack and when we extract the words, they will be in reverse order.