JAVA A palindrome is a string that reads the same forwards o

JAVA!!!

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.

Solution

import java.util.*;

import java.lang.*;

class Palindrome{

public isPalindrome(String string)

{

if(string.length()==0 || string.lenght()==1) // this will check for empty string or if string contains just one letter then //true

return true;

if(string.charAt(0) == string.charAt(string.length()-1) //this check the first character and last character

return isPalindrome(string.substring(1,string.lenght()-1); //here we are calling the same method recursively by //sending the substring everytime which starts from first character and last character. Now here everytime first and //character from last iteration will be the next one in sequence.this way we will iterate through complete string until it fails and goes to below iteration

return false;

}

public static void main(String args[])

{

Scanner s = new Scanner(System,in);

System.out.println(\"Enter the string to be checked\");

String s = s.nextLine();

//check in if condition by passing this string to the above defined function

if(isPalindrome(s)

System.out.println(\"Entered string is palindrome\");

else

System.out.println(\"Entered string is not palindrome\");

}

}

JAVA!!! 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 ).

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site