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)?
Anyway cookamunga provided good inline solution using python!
Actually, the first answer:
does not work because it undoes in the second half of the loop the work it did in the first half. So, i < words.length/2 would work, but a clearer example is this:
Note: I am not familiar with the PHP syntax, and I have guessed incrementer and decrementer syntax since it seems to be similar to Perl.
You cannot do the reversal without at least some extra data structure. I think the smallest structure would be a single character as a buffer while you swap letters. It can still be considered "in place", but it's not completely "extra data structure free".
Below is code implementing what Bill the Lizard describes:
What language? If PHP, you can explode on space, then pass the result to array_reverse.
If its not PHP, you'll have to do something slightly more complex like:
c# solution to reverse words in a sentence
output: peaople the of heart the in lies beauty Press any key to continue . . .
This is C# code.