Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

A palindrome is a string that reads the same forwards or backwards; for example

ID: 3570209 • Letter: A

Question

A palindrome is a string that reads the same forwards or backwards; for example dad, mom, deed (i.e., reversing a palindrome produces the same string ). Write a recursive, boolean -valued  method , isPalindrome that accepts a string and returns whether the string is a palindrome.
A string , s, is a palindrome if:

s is the empty string or s consists of a single letter (which reads the same back or forward), or

the first and last characters of s are the same, and the rest of the string (i.e., the second through next-to-last characters ) form a palindrome.

Explanation / Answer

import java.io.*;
import java.lang.*;
import java.util.*;
public class HelloWorld{

static boolean isPalindrome(String str){
//Base Case: s is the empty string or s consists of a single letter
//Return true in this case
if(str.length() == 0 || str.length() == 1) return true;
  
//recursion if first and last characters are same
if(str.charAt(0) == str.charAt(str.length()-1))
return isPalindrome(str.substring(1,str.length()-1));
  
//If first and last are not same, return false
return false;
}

public static void main(String []args){
System.out.println(isPalindrome("mom"));
System.out.println(isPalindrome("dad"));
System.out.println(isPalindrome("deed"));
System.out.println(isPalindrome("dead"));
}
}

//Sample output

sh-4.2# javac HelloWorld.java                                          

sh-4.2# java -Xmx128M -Xms16M HelloWorld                               

true                                                                   

true                                                                   

true                                                                   

false

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote