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)?
In Java using an additional String (with StringBuilder):
In Java in-place:
Most of these answers fail to account for leading and/or trailing spaces in the input string. Consider the case of
str=" Hello world"
... The simple algo of reversing the whole string and reversing individual words winds up flipping delimiters resulting inf(str) == "world Hello "
.The OP said "I want to reverse the order of the words" and did not mention that leading and trailing spaces should also be flipped! So, although there are a ton of answers already, I'll provide a [hopefully] more correct one in C++:
My version of using stack:
I know there are several correct answers. Here is the one in C that I came up with. This is an implementation of the excepted answer. Time complexity is O(n) and no extra string is used.
reverse the string and then, in a second pass, reverse each word...
in c#, completely in-place without additional arrays: