Home » Java » recursive method that checks if a string is palindrome in java-Exceptionshub

recursive method that checks if a string is palindrome in java-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

the input: “mnkknm” where n=0
the output: flag is always equal 1 while it should be equal 3
and it returns -1
what is the problem ?
note : palindrome means for example if the Reverse of malayalam is also
malayalam then its palindrome
another note : i should write the code recursive as it’s a homework

public static int PalindromeCheck(String x , int n) 
{

int flag =0;
if (n+1 !=x.length()/2)
{
char s = x.charAt(n);
char y = x.charAt(x.length()-1-n);
if (s==y)
{    flag++;
System.out.println(flag); // i write it to check the value of the flag
}

return  flag+PalindromeCheck(x,n+1) ;
}

if (flag==x.length()/2)
{
return 1;}
else{
return -1;
}
How to&Answers:

try this method please

public static boolean isPal(String s)
{
    if(s.length() == 0 || s.length() == 1) {
        return true;
    }
    if(s.charAt(0) == s.charAt(s.length()-1)) {

        return isPal(s.substring(1, s.length() - 1));
    }
    return false;
}

Answer:

First, I would create a helped method with that recursive signature (the public function should just take a String). And we can test for null and the empty string as special cases there. Like,

public static boolean isPalindrome(String x) {
    if (x == null) {
        return false;
    } else if (x.isEmpty()) {
        return true;
    }
    return isPalindrome(x, 0);
}

Then your current method seems close, but you want to compare n with a less than operator to the half of the length of x. Then test that the character matches on the right hand side (offset by n from x.length() but we need a -1 because of zero based indexing). Also, the method should return a boolean (and I fixed the name). Like

private static boolean isPalindrome(String x, int n) {
    if (n < x.length() / 2) {
        if (x.charAt(n) != x.charAt(x.length() - n - 1)) {
            return false;
        }
        return isPalindrome(x, n + 1);
    }
    return true;
}