A palindrome is a string that reads the same forwards or backwards; for example
ID: 3658938 • 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, bool-valued function, 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
public class Palindrome
{
private static boolean isPalindrome(String word)
{
if(word.length()==1)
{
return true;
}
else if(word.charAt(0) == word.charAt(word.length()-1) )
{
return isPalindrome(word.substring(1,word.length()-1));
}
else
{
return false;
}
}
public static void main(String[] args)
{
String word ="malayalam";
if(isPalindrome(word))
{
System.out.println(word + " is a palindrome");
}
else
{
System.out.println(word + " is not a palindrome");
}
}
}
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.