Recursive Methods as a Problem Solving Techique - Part 3

  1. Sometimes the smaller subproblem(s) need to be solved AFTER you solved the "Problem X"

  2. Example: Palindrome

    Recursive solution for IsPalindrome:
    
       static boolean IsPalindrome(String s)
       {
          if ( s.length() == 0 )
          {  // Base case 1: "" is a palindrome
             return(true);
          }
          else if ( s.length() == 1 )
          {  // Base case 2: "x" is a palindrome - for any letter x
             return(true);
          }
          else
          {
    	 boolean SolX, Sol;
    
             // Check first and last character:
             if ( s.charAt(0) != s.charAt( s.length() - 1 ) )
             {  // For sure not a palindrome...
                return(false);
             }
    
             // ************************
             // Solve smaller problem: 
    	 //     Test palindrome for a string with the first 
    	 //     and last char OMITTED !
             // ************************
             Sol = isPalindrome(  s.substring(1, s.length()-1) );
    
    	 SolX = Sol;     // How to use the solution of smaller problem
    			 // to solve bigger problem
             return(SolX);
          }
    
       }
    
    

  3. How the recursion works (it you understand the principles, this is getting a bit boring...)

    Example: IsPalindrome("racecar")
    
    

  4. DEMO program: click here