check for palindrome recursion code example
Example 1: Java program to check palindrome string using recursion
import java.util.Scanner;
public class RecursivePalindromeJava
{
public static boolean checkPalindrome(String str)
{
if(str.length() == 0 || str.length() == 1)
return true;
if(str.charAt(0) == str.charAt(str.length() - 1))
return checkPalindrome(str.substring(1, str.length() - 1));
return false;
}
public static void main(String[]args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a string : ");
String strInput = sc.nextLine();
if(checkPalindrome(strInput))
{
System.out.println(strInput + " is palindrome");
}
else
{
System.out.println(strInput + " not a palindrome");
}
sc.close();
}
}
Example 2: reads the string in then determines if the string is a palindrome.
#include <iostream>
using namespace std;
bool isPalindrome(string str, int low, int high)
{
if (low >= high)
return true;
if (str[low] != str[high])
return false;
return isPalindrome(str, low + 1, high - 1);
}
int main()
{
string str = "XYBYBYX";
int len = str.length();
if (isPalindrome(str, 0, len - 1))
cout << "Palindrome";
else
cout << "Not Palindrome";
return 0;
}