Java – recursively tests whether the character array is a palindrome

I tried to find a solution, but all the solutions I found were strings What I want to do is check whether the character array entered by the user is a palindrome This is what I have so far:

public static boolean palCheck(char[] a,int index,int start) {
    if (a[start] != a[index]){
        return false; //base case
    }
    else if(a[start+1] == a[index]){
        palCheck (a,index-1,start+1);
        return true; //recursive step
    } 
    else 
        return false;
}

If the first and last elements of the array are the same, it always returns true What did I do wrong? Thank you in advance!

Solution

You return true on an equal basis, not your recursive solution You also need to check when the index is out of range or equal so that after you confirm that it is a palindrome, your function will terminate

Edit:

public static boolean palCheck(char[] a,int start) {
    if (index <= start) { 
        return true; 
    }
    if (a[start] != a[index]){
        return false; //base case
    } else {
        return palCheck (a,start+1); //recursive step
    } 
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>