Re: Reverse words in a string (Another Interview question)



Sc0rpi0 wrote:
) Willem:
)
)> Anyway, the simplest way, and probably the most efficient, would be to
)> allocate room for a new string, and then just copy the string word by
)> word, in reverse order.
)
) Simplest I think is not to allocate room for a new string.
) Just reverse, first in words wchich we just simply find (start-end),
) each one reverse using half of word length number of steps:
)
) like blahblah-> hlahblab->...->hlabhlab
) ^ ^ ^ ^ ^^
) then reverse entire string same way.

That's two passes, and I find it more complicated.
The only benefit is that you don't have to allocate a new string.

) Not too slow, and no extra memory is used - i think it's OK.
) Of course it is slower than copying right away in reverse order,
) and cannot be done with consts (i.e. "string example" in C),
) but is simple and nice and uses no memory extra.
)
) Anoter one way is to search words from two ends, and replace
) at once. But have no time to think about it right now ;P.
) (and yes, I know words don't have to be equal length).

That's going to be a pain in the ***, but it can be done.
No way is it simple, though. I had the same idea but it works out
to be ridiculously complicated. Obfuscated C material, I say.


SaSW, Willem
--
Disclaimer: I am in no way responsible for any of the statements
made in the above text. For all I know I might be
drugged or something..
No I'm not paranoid. You all think I'm paranoid, don't you !
#EOT
.


Quantcast