Search code examples
javarecursionpalindrome

Palindrome with recursion; index out of bound


I'm trying to write a function that checks whether a string variable is a palindrome or not. I can't find the reason this code throws IndexOutOfBoundException. I've tried to use examples so as to follow the result, but I still can't see where the exception is from.

public static boolean palindrome(String s) {
    if (s.charAt(0) == s.charAt(s.length() - 1)) {
        if (s.length() > 2) {       
            StdOut.print(s.substring(1, s.length() - 2));
            palindrome(s.substring(1, s.length() - 2));
        } else
            return true;
    }
    return false;
}

Solution

  • Try this:

    public static boolean palindrome(String s)
    {
        if (s.length() < 2)
            return true;
        if (s.charAt(0) != s.charAt(s.length()-1))
            return false;
        return palindrome(s.substring(1,s.length()-1));
    }