Top Java Interview Question : reverse a string using recursion

Best Answer using Recursion :

  public String reverse(String str) {
     if ((null == str) || (str.length()  <= 1)) {
        return str;
      }
    return reverse(str.substring(1)) + str.charAt(0);
   }


Less Best Answer :
public class JdkReverser implements Reverser {
  public String reverse(String str) {
     if ((null == str) || (str.length() <= 1)) {
         return str;
      }
     return new StringBuffer(str).reverse().toString();
  }
}

No comments :

Post a Comment

Your Comment and Question will help to make this blog better...