Assume that s is a string of characters such that each character belongs to the
ID: 3690393 • Letter: A
Question
Assume that s is a string of characters such that each character belongs to the English alphabet {a, b, c, d, ……., x, y, z}. The string s is called a palindrome if we get two identical strings when we read s forwards and backwards.Write a recursive function called Palindrome with signature “public static Boolean Palindrome (String string1, int first, int last)” that returns true if the substring from first to last of string1 is a palindrome or false if string1 is not a palindrome. Also, write a java program to test your function.
Explanation / Answer
import java.util.Scanner;
class Palind
{
public static Boolean Palindrome (String string1, int first, int last)
{
// if length is 0 or 1 then String is palindrome
if(first==last)
return true;
if(string1.charAt(first) == string1.charAt(last))
//if character at first is same as character at last recursively call function
return Palindrome(string1,first+1,last-1);
return false;
}
public static void main(String[]args)
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the String:");
String string = scanner.nextLine();
//If function returns true then the string is palindrome else not
if(Palindrome(string,0,string.length()-1))
System.out.println(string + " is a palindrome");
else
System.out.println(string + " is not a palindrome");
}
}