HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaModerate

Recursive implementation of palindrome string checker

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
palindromerecursiveimplementationstringchecker

Problem

I've tried to refactor my program to single return statement at the end of the program, however, it ruins the end statements of the recursion because I want to return from function in specific line and not in the end of the function.

I'd like suggestions on how this code can work and be elegantly designed to comply with

  • Multiple return statements



  • Single return statement



private static boolean isPalindrome(String pal)
{   
        if(pal.length() == 1 || pal.length() == 2 )
        {
            if(pal.length()==1)
            {
                return true;
            }

            else
            {
                if(pal.charAt(0) == pal.charAt(1))
                {
                    return true;
                }
                return false;
            }           
        }

        else
        {
            if(pal.charAt(0) == pal.charAt(pal.length()-1))
            {
                return isPalidrome(pal.substring(1, pal.length()-1));
            }
            return false;
        }
    }
}

Solution

For all practical purposes, recursion is a bad idea for this problem, mainly because String.substring() is an expensive operation, especially since Java 7. Let's assume that you're doing this just as a fun educational exercise.

Single return statements are overrated. There's no practical advantage to forcing your code to have just one return for its own sake.

Your base cases are poorly chosen. A zero-length string will cause a crash. If you handle empty strings as a base case, then you no longer need to treat two-character strings as a special case.

You take the string length often enough that it's worth assigning it to a variable.

Overall, the function could be written more compactly.

public static boolean isPalindrome(String s) {
    int len = s.length();
    if (len <= 1) {
        return true;
    }
    return (s.charAt(0) == s.charAt(len - 1)) &&
           isPalindrome(s.substring(1, len - 1));
}

Code Snippets

public static boolean isPalindrome(String s) {
    int len = s.length();
    if (len <= 1) {
        return true;
    }
    return (s.charAt(0) == s.charAt(len - 1)) &&
           isPalindrome(s.substring(1, len - 1));
}

Context

StackExchange Code Review Q#55015, answer score: 14

Revisions (0)

No revisions yet.