Friday, April 30, 2010

Reverse a string

Question

Write code to reverse a string in its place.

Answer

[ This basically means, that we cannot allocate extra memory for the reversed string and have to return it back in the same memory ]

To reverse a string in its place, we'll have to swap the 1st character with the nth character, then the 2nd character with the (n - 1)th character and so on ...


Corollary Question

Reverse the string in its place, without using a temporary variable.

Answer

The logic for this comes from the simple swapping technique that does not use a temporary variable.


Using the above logic we can re-write our function to reverse the string as below

No comments:

Post a Comment