Friday, January 6, 2012

Reverse a String

A typical programming interview question is “reverse a string, in place”. if you understand pointers, the solution is simple. even if you don’t, it can be accomplished using array indices


to reverse the string word by word, in place. for example if our string is “the house is blue”, the return value would be “blue is house the”. the words are reversed, but the letters are still in order


initial: the house is blue
reverse: eulb si esuoh eht
wanted : blue is house the

the solution can be attained by first reversing the string normally, and then just reversing each word.

Reference:
http://www.techinterview.org/post/526374214/reverse-a-string





  • 3-ways to reverse a string in java



First Solution: StringBuffer
The easiest way to reverse a String in Java is by using an instance of the StringBuffer class as it already contains a reverse() method.


Second Solution: Reverse For Loop
You can also reverse a String by traversing it from the end in a traditional for loop. For this approach you can either use a char array which would be somewhat more efficient than by creating a large String pool as a result of continuous concatenation to a String variable.

Third Solution: Recursion

http://www.brilliantsheep.com/3-ways-to-reverse-a-string-in-java/

No comments:

Post a Comment