Computing Palindrome using Recursion in Java

Recursion means a method; calling directly or indirectly themselves. Recursion is a useful programming technique. In some cases, it enables you to develop a straightforward and simple solution to an otherwise difficult problem. This post introduces you how to String Palindrome using Recursion in Java. 

Lets calculate the Palindrome of a string using recursion: 

RecursivePalindrome.java


public class RecursivePalindrome {

       public static boolean isPalindrome(String s) {

              if (s.length() <= 1) {
                     // Base case
                     return true;
              } else if (s.charAt(0) != s.charAt(s.length() - 1)) {
                     // Base case
                     return false;
              }

              else {
                     // recursive call
                     return isPalindrome(s.substring(1, s.length() - 1));
              }
       }

     public static void main(String[] args) {
       System.out.println("Is xyx a palindrome? " + isPalindrome("xyz"));
       System.out.println("Is nan a palindrome? " + isPalindrome("nan"));
       System.out.println("Is a a palindrome? " + isPalindrome("a"));
       System.out.println("Is aba a palindrome? " + isPalindrome("aba"));
       System.out.println("Is abb a palindrome? " + isPalindrome("abb"));
     }
}
  


Output of the above code listing would look like:
     Is xyx a palindrome? false
    Is nan a palindrome? true
    Is a a palindrome? true
    Is aba a palindrome? true
    Is abb a palindrome? false

 

Newer Post Older Post

Leave a Reply

naeemgik. Powered by Blogger.