Search code examples
methodspalindromestack-overflow

StackOverflow error for Palindrome using recursive syntax


I'm making a program that checks for a Palindrome using recursive syntax. Unfortunately, it continues generating a run-time error saying "stackOverFlow error" and although I've done researching I can't seem to understand as to why its occurring. This is the method that is currently undergoing repair.

public static void check(String s, int n)
    {
        String s1 = s;
        if(s.length() < 1)
        {
            System.out.println("This is always a palindrome");       
            ans = true;
        }
        else if(s.length() > 1)
        {
            if(s.charAt(n-1) == s1.charAt(n-1))
            {
                ans = true;
            }
            else
            {
                ans = false;
            }
            check(s, n);

        } 
        if(ans == true)
        {
            System.out.println("This is a palindrome!");
        }
        else
        {

            System.out.println("This isn't a palindrome!");
        }

Solution

  • Complementing Ransom's point, the comparison

    s.charAt(n-1) == s1.charAt(n-1)
    

    will always return true.

    Try to construct the recursive algorithm like this:

       check(s){
          // insert code: if length is 0 or 1, always return true;
          if(s.chatAt(0) == s.charAt(s.length-1))
               return check(s.subString(1,length-1))
      }
    

    The key points are:

    1. For a recursive algorithm, you cannot put exactly the same function within it self with the same parameters like

       check(s){
           check(s)
       }
      

    This will result in overflow;

    1. You must return something from the inner loop to the outer loop. Hope this helps.