-1

I tried to use recursion to solve the palindrome problem. I got a Exception in thread "main" java.lang.StackOverflowError at java.lang.String.substring(String.java:1969) at Main.isPalindrome(Main.java:160)

However, I don't know how to fix it.

public static boolean isPalindrome(String s) {
        int len = s.length();
        if (len <= 1) return true;
        else {
            char ch1 = Character.toLowerCase(s.charAt(0));
            char ch2 = Character.toLowerCase(s.charAt(len - 1));
            boolean check1 = Character.isLetter(ch1) || Character.isDigit(ch1);
            boolean check2 = Character.isLetter(ch2) || Character.isDigit(ch2);
            if (check1 && check2) {
                if (ch1 == ch2) {
                    String shorter = s.substring(1, len - 1);
                    return isPalindrome(shorter);
                }
                else {
                    return false;
                }
            }
            else if (!check1 && check2) {
                String shorter = s.substring(1);
                return isPalindrome(shorter);
            }
            else if (!check2 && check1) {
                String shorter = s.substring(0, len - 1);
                return isPalindrome(shorter);
            }
            else {
                String shorter = s.substring(1, len - 1);
                return isPalindrome(shorter);
            }
        }
    }
mhasan
  • 3,703
  • 1
  • 18
  • 37
sower
  • 71
  • 1
  • 5
  • here your code is assuming that the input string will be off odd length. Check if the length is 2 in the start block also and check at 0th and 1st position then – Kishan Kumar Oct 08 '16 at 04:29
  • I tried System.out.print(isPalindrome("sb,bbs")); System.out.print(isPalindrome(",bbs")); System.out.print(isPalindrome("sbbs")); – sower Oct 08 '16 at 04:47
  • But all of them are correct – sower Oct 08 '16 at 04:47

2 Answers2

0

It's hard to say without knowing exactly which line is 160. That said, you are probably calling that with the same arguments as the method itself, and there is consequently nothing to end your recursion.

Joe C
  • 15,324
  • 8
  • 38
  • 50
0

Nothing wrong with your logic. It's just that there's a limited amount of memory to keep the stack frames, and therefore a limited number of recursion levels. When the input string is large enough StackOverflowError would be thrown.

My suggestion is to abandon this recursive implementation and use a loop instead.

Worakarn Isaratham
  • 1,034
  • 1
  • 9
  • 16