Chapter 16. PC #5. Palindrome Detector (page 1073) A palindrome is any word, phr
ID: 3844647 • Letter: C
Question
Chapter 16. PC #5. Palindrome Detector (page 1073)
A palindrome is any word, phrase, or sentence that reads the same forward and backward. Here are some well-known palindromes:
Able was I, ere I saw Elba
A man, a plan, a canal, Panama
Desserts, I stressed
Kayak
Write a (JAVA) boolean method that uses RECURSION to determine whether a String argument is a palindrome. The method should return true if the argument reads the same forward and backward. Demonstrate the method in a program.
The program should ask the user to enter a string, which is checked for palindrome property. The program displays whether the given input is a palindrome or not, then prompts the user to enter another string. If the user enters QUIT (case insensitive, then exit the program).
Explanation / Answer
One approach to check palindrome using recursion is to check first and last character for a match, if it matches then pass the substring with first and last character removed to the same function recursively, until we get length of string as 0 or 1. If at any point in between first and last character does'nt match return false.
We have to clean the input string at first, that is remove white spaces, commas and dots and convert entire string to lower case. For that I have used replaceAll() and toLowerCase() .
Below is the entire program:
/* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
class palindrome
{
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) throws java.lang.Exception
{
Scanner sc=new Scanner(System.in);
while(true){
String input=sc.nextLine();
//if quit encountered come out of loop
if(input.equalsIgnoreCase("quit"))
break;
//remove all spaces, commas and dots
String cleanString = input.replaceAll("[, . \s]", "").toLowerCase();
if(checkPalindrome(cleanString))
System.out.println(input+" is palindrome");
else
System.out.println(input+" is NOT palindrome");
}
}
}
Sample Input:
Able was I, ere I saw Elba
A man, a plan, a canal, Panama
Desserts, I stressed
Kayak
sdf
QUIT
Sample output:
Able was I, ere I saw Elba is palindrome
A man, a plan, a canal, Panama is palindrome
Desserts, I stressed is palindrome
Kayak is palindrome
sdf is NOT palindrome
Please give a thumbs up if you liked the solution
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.