Question

I have written a recursive method to check if a word is a palindrome or not.

But I now also wish to check for any special characters (*?!< in the string. So if the string is ab.ba it is not a palindrome.

Here is what I have and the isAlphanuemerical() seems to be working ok when stepping through it, but it still registers as a palindrome if I enter ab.ba

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

    // Check if String contains any alphanumeric characters
    if (isAlphanumeric(s))
        return false;


    if(s.charAt(0) == s.charAt(s.length()-1))
        return isPal(s.substring(1, s.length()-1));//if its not the case than string is not.
    return false;
}

And my isAlphaneumerical() method

public static boolean isAlphanumeric(String str) {
    for (int i = 0; i < str.length(); i++) {
        char c = str.charAt(i);
        if (!Character.isLetter(c) && !Character.isDigit(c))
            return false;
    }
    return true;
}
Was it helpful?

Solution

if (isAlphanumeric(s))
        return false;

Should be

if (!isAlphanumeric(s))
        return false;

Also, you don't need to call isAlphanumeric(s) EVERYTIME. You could call it once, or change it so it only checks the first/last characters. You're checking something that was already checked before.

public static boolean isPal(String s)
{
    if (!isAlphanumeric(s))
        return false;

    return _isPal(s);
}

private 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;
}

private static boolean isAlphanumeric(String str) 
{
    for (int i = 0; i < str.length(); i++) 
    {
        char c = str.charAt(i);

        if (!Character.isLetter(c) && !Character.isDigit(c))
            return false;
    }
    return true;
}

OTHER TIPS

Your code is doing exactly what you told it to do. The isAlphanumeric method works fine.

But your isPal returns false if it is alphanumeric.

If you don't wan't non-alphanumeric strings to be palindromes, then reverse your logic:

if (!isAlphanumeric(s))
    return false;

This uses the ! operator to negate the boolean result.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top