Check is given String is a Palindrome in Java using Recursion

 


Here is our Java program, which checks if a given String is palindrome or not. The program is simple, and here are steps to find palindrome String :

1) Reverse the given String
2) Check if the reverse of String is equal to itself; if yes, then given String is a palindrome.

In our solution, we have a static method isPalindromeString(String text), which accepts a String. It then calls the reverse(String text) method to reverse this String. This method uses Recursion to reverse String. This function first checks if the given String is null or empty, if yes then it returns the same String because they don't require to be reversed.

After this validation, it extracts the last character of String and passes rest or String using substring() method to this method itself, hence the recursive solution. The validation also servers as base case because, after every step, String keeps getting reduced, and eventually it will become empty, there your function will stop Recursion and will use String concatenation to concatenate all character in reverse order. Finally, this method returns the reverse of String.

When the call to reverse() returns back, isPalindromeString(String text) uses the equals() method to check if the reverse of String is equal to the original String or not, if yes then it returns true, which also means String is a palindrome.

As I said if you are looking for more coding-based problems you can also always check the Grokking the Coding Interview: Patterns for Coding Questions course on Educative, one of the great courses to build coding sense and pattern recognition required to clear programming interviews.


How to check if String is Palindrome in Java using Recursion

Here is the complete Java program to check if the given String is palindrome or not. In this program, we have used Recursion to first reverse the String and then check if both original and reversed String is the same or not.

// A recursive JAVA program to
// check whether a given String
// is palindrome or not
import java.io.*;

class CollegeMantra
{
// A recursive function that
// check a str(s..e) is
// palindrome or not.
static boolean isPalRec(String str,
int s, int e)
{
// If there is only one character
if (s == e)
return true;

// If first and last
// characters do not match
if ((str.charAt(s)) != (str.charAt(e)))
return false;

// If there are more than
// two characters, check if
// middle substring is also
// palindrome or not.
if (s < e + 1)
return isPalRec(str, s + 1, e - 1);

return true;
}

static boolean isPalindrome(String str)
{
int n = str.length();

// An empty string is
// considered as palindrome
if (n == 0)
return true;

return isPalRec(str, 0, n - 1);
}

// Driver Code
public static void main(String args[])
{
String str = "geeg";

if (isPalindrome(str))
System.out.println("Yes");
else
System.out.println("No");
}
}






1 Comments

Post a Comment
Previous Post Next Post