wannamd
wannamd

Reputation: 23

String out of bound error with even numbered length strings

I have written my version of method that tests whether a word is a palindrome or not. It seems to work well with odd numbered length strings but String Out of Bound Exception error occurs when tested with even numbered length.

Any help would be appreciated!

public static boolean palindrome(String s, int start, int end) {

int length = s.length();


        if (length%2 != 0 && start != end) {
            if (s.charAt(start) == s.charAt(end)) {
                return palindrome(s,start+1,end-1);
            }
            else {
                return false;
            }
        }
        else if(length%2 == 0 && (start+1) != (end-1)) {
            if (s.charAt(start) == s.charAt(end)) {
                return palindrome(s,start+1,end-1);
            }
            else {
                return false;
            }
        }
        else if(length%2 != 0 && start == end) {
            return true;
        }
        else if(length%2 == 0 && start+1 == end-1) {
            if (s.charAt(start+1) == s.charAt(end-1)) {
                return true;
            }
            else {
                return false;
            }
        }
        else {
            return false;
        }

    }

Upvotes: 0

Views: 68

Answers (1)

Dimitris
Dimitris

Reputation: 589

I think your code is a bit unnecessary complicated, you are using indexes to do what you can do with substring in java. Also, you have many cases for even or odd numbers that you could avoid, by just considering them in your base case. I tried to keep your approach and reduced the code as much as possible. I think is much cleaner. In the base case if the number is odd it will end up at the 1 and if it is even it will end up at 2.

public boolean isPalindrome(String string)
{
    if (string.length() > 2) {
        if (string.charAt(0) == string.charAt(string.length() - 1)) {
            return this.isPalindrome(string.substring(1, string.length() - 1));
        } else {
            return false;
        }
    } else if (string.length() == 1) {
        return true;
    } else {
        if (string.charAt(0) == string.charAt(1)) {
            return true;
        } else {
            return false;
        }
    }
}

Upvotes: 1

Related Questions