Phoenix
Phoenix

Reputation: 8923

Is this the most efficient way of doing recursion for checking whether a string is a palindrome?

public boolean isPalindrome3(String input, int index, int length)
{
    if(index > (length-1-index))
        return true;

    else if(input.charAt(index)!=input.charAt(length-1-index))
        return false;

    else
        return isPalindrome3(input, index + 1, length);



}

Here initially i pass the input string, 0, input.length()

Upvotes: 0

Views: 712

Answers (3)

pgardunoc
pgardunoc

Reputation: 331

public static String reverseString(String s) {       
    byte[] array = s.getBytes();
    byte swap;

    for( int i = 0, j = array.length - 1; i < array.length / 2; i++, j--) {
        swap = array[ j ];
        array[ j ] = array[ i ];
        array[ i ] = swap;
    }

    return (new String(array));
}

if(myString.equals(reverseString(myString)))
    // is palindrome

Upvotes: 0

Ted Hopp
Ted Hopp

Reputation: 234795

If you don't have to use recursion, here's a much more efficient check for palindrome:

public boolean isPalindrome3(String input)
{
    for (int start = 0, end = input.length() - 1; start < end; ) {
        if (input.charAt(start++) != input.charAt(end--)) {
            return false;
        }
    }
    return true;
}

Upvotes: 3

Martijn Courteaux
Martijn Courteaux

Reputation: 68847

I would write it like this:

public boolean isPalindrome(String str, int offset)
{    
    int rightOffset = str.length() - offset - 1;
    if (offset <= rightOffset)
    {
        char c1 = str.charAt(offset);
        char c2 = str.charAt(rightOffset);
        if (c1 != c2) return false;

        return isPalindrome(str, offset + 1);
    } else
    {
        return true;
    }
}

Differences with your code:

  • Do not pass the length, because that is a String property
  • unwrap the character comparation
  • nice code formatting
  • improved efficiency, by creating a local variable rightOffset.

Upvotes: 0

Related Questions