Write a recursive program to check if a string is a palindrome? The method returns a boolean to indicate if the string is a palindrome or not. [4 pts]What is the time complexity of your algorithm? [2 pts] code example
Example 1: Java program to check palindrome string using recursion
import java.util.Scanner;
public class RecursivePalindromeJava
{
// to check if string is palindrome using recursion
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.
using namespace std;
// Iterative function to check if given string is a palindrome or not
bool isPalindrome(string str)
{
int low = 0;
int high = str.length() - 1;
while (low < high)
{
// if mismatch happens
if (str[low] != str[high])
return false;
low++;
high--;
}
return true;
}
int main()
{
string str = "XYXYX";
if (isPalindrome(str))
cout << "Palindrome";
else
cout << "Not Palindrome";
return 0;
}