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)?
Here is a C implementation that is doing the word reversing inlace, and it has
O(n)
complexity.In c, this is how you might do it, O(N) and only using O(1) data structures (i.e. a char).
This is not perfect but it works for me right now. I don't know if it has O(n) running time btw (still studying it ^^) but it uses one additional array to fulfill the task.
It is probably not the best answer to your problem because i use a dest string to save the reversed version instead of replacing each words in the source string. The problem is that i use a local stack variable named buf to copy all the words in and i can not copy but into the source string as this would lead to a crash if the source string is const char * type.
But it was my first attempt to write s.th. like this :) Ok enough blablub. here is code:
Printing words in reverse order of a given statement using C#:
This quick program works..not checks the corner cases though.
Store Each word as a string in array then print from end