Tuesday, November 3, 2015

Palindrome String Check Recursively in Java

Palindrome String checking is one of the primitive exercises for String processing char-by-char.

Palindrome String check can also be implemented recursively in Java. This recursive implementation is not efficient as the iterative one because it calls String.substring() subsequently.



package basics;

public class StringUtils {

 public static boolean isPalindrome( String str )
 {
  int sLength = str.length();
  if ( sLength < 2) {
   return true;
  } else if ( str.charAt(0) != str.charAt( sLength-1 ) ) {
   return false; 
  } else if ( sLength == 2 ) {
   return true;
  } else { 
   return isPalindrome( str.substring( 1, sLength-1 ));
  }
  
 }
 
 public static void main(String[] args) {
  
  String str = "madam";
  boolean result = isPalindrome(str);
  System.out.println(str+" is Palindrome = "+result);
  
  str = "qqaacc";
  result = isPalindrome(str);
  System.out.println(str+" is Palindrome = "+result);
  
  str = "cocoococ";
  result = isPalindrome(str);
  System.out.println(str+" is Palindrome = "+result);
 }
}



Create a StringUtils.java file in your workspace.

When the main method inside the StringUtils class executed it is going to print :

madam is Palindrome = true
qqaacc is Palindrome = false
cocoococ is Palindrome = true

2 comments:

  1. If sLength == 2, then how it is a palindrome? I am confused.

    ReplyDelete
  2. This if statement is part of the "else-if" code block. Code is not directly checking for the length of the stringLength==2 to make a decision. After passing above else-if statement, if the length of the current string is 2 then it becomes a palindrome. You can debug it with String variables "aa" and "ab" to see the difference.

    ReplyDelete