You are on page 1of 2

import java.util.

Scanner;
public class JavaApplication8 {
private String pal;
public JavaApplication8(String initPal) {
pal = initPal.toUpperCase();
}
public boolean isPalindrome() {
if (pal.length() <= 1) {
// String has only one character so it
// is a Palindrome by definition.
return true;
// BASE CASE.
}
// Get the first and last characters of the String.
char first = pal.charAt(0);
char last = pal.charAt(pal.length()-1);
if (Character.isLetter(first) &&
Character.isLetter(last)) {
// The first and last characters are both letters..
if (first != last) {
// The first and last letters are different
// so the string is not a Palindrome.
return false;
// BASE CASE.
}
else {
// The first and last characters are both letters,
// and they are both the same. So, the string is
// a palindrome if the substring created by dropping
// the first and last characters is a palindrome.
JavaApplication8 sub = new JavaApplication8(
pal.substring(1,pal.length()-1));
return sub.isPalindrome(); // RECURSIVE CASE.
}
}
else if (!Character.isLetter(first)) {
// The first character in the string is not a letter.
// So the string is a palindrome if the substring created
// by dropping the first character is a palindrome.
JavaApplication8 sub = new JavaApplication8(pal.substring(1));
return sub.isPalindrome();
// RECURSIVE CASE.
}
else {
// The last character in the string is not a letter.
// So the string is a palindrome if the substring created
// by dropping the last character is a palindrome.
JavaApplication8 sub = new JavaApplication8(
pal.substring(0,pal.length()-1));
return sub.isPalindrome();
// RECURSIVE CASE.
}
}
public static void main(String[] args) {
String str="";
Scanner scan = new Scanner(System.in);
System.out.println("Enter the String");

str = scan.nextLine();
JavaApplication8 p1 = new JavaApplication8(str);
if(p1.isPalindrome())
System.out.println("Palindrome");
else
System.out.println("Not a Palindrome");
}
}

You might also like