Reverse a String

Write a method that reverses a given String.

There are 3 ways that I know how you can reverse a String

1) for-loop
2) recursion
3) StringBuilder (applicable only using Java)

public class ReverseString {

public static void main(String[] args){
  System.out.println("\nReverse a String using StringBuilder: " + 
      reverse("hello"));
  System.out.println("Reverse a String using Recursion: " + 
      reverseUsingRecursion("hello"));
  System.out.println("Reverse a String using For Loop: " + 
      reverseUsingFor("hello"));
}

private static String reverse(String input){
  return new StringBuilder(input).reverse().toString();
}

private static String reverseUsingRecursion(String input){
  // A recursion should always has an exit condition/statement
  if(input == null || input.length() <= 1){
    return input;
  }
  
  // put the first character (i.e charAt(0)) to the end.
  // and recurse with 2nd character (.e subString(1)) onwards

  return reverseUsingRecursion(input.substring(1)) + input.charAt(0);
}

private static String reverseUsingFor(String input){
  if((null == input) || (input.length() <= 1)){
    return input;
  }
  char[] chars = input.toCharArray();
  int rhsIndex = chars.length - 1;
  // iteratively swap until exit condition lhsIndex < rhsIndex is reached
  for(int lhsIndex = 0; lhsIndex < rhsIndex; lhsIndex++){
    char temp = chars[lhsIndex];
    chars[lhsIndex] = chars[rhsIndex];
    chars[rhsIndex--] = temp;
   }
   return new String(chars);
 }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s