Search code examples
javapalindrome

Why do I get a StringOutOfBoundsException even though I am within bounds of the String array?


I'm currently attempting this problem and seem to keep getting this StringOutOfBoundsException, can anyone explain to me why? When I exit the while loop, it seems that I mistyped endPtr--;

StringOutOfBoundsException

class Solution {
    public boolean isPalindrome(String s) {
        if (s == null) {
            throw new IllegalArgumentException("Illegal input!");
        }
        if (s.length() <= 1) {
            return true;
        }
        
        int startPtr = 0;
        int endPtr = s.length() - 1;
        
        while (startPtr < endPtr) {
            while (startPtr < endPtr && !Character.isLetterOrDigit(s.charAt(startPtr))) {
                startPtr++;
            }
            
            //ERROR while (startPtr < endPtr && !Character.isLetterOrDigit(s.charAt(endPtr)))  {
                //endPtr--;
            //}
            
            if (startPtr < endPtr && Character.toLowerCase(s.charAt(startPtr)) != Character.toLowerCase(s.charAt(endPtr))) {
                return false;
            }
        
            startPtr++;
            endPtr++;
        }
        return true;
    }
}

Solution

  • In the end of the main loop, you are incrementing endPtr.

        startPtr++;
        endPtr++;
    

    By doing so, you are positionning the end of your String after its real ending.

    And here comes the error.

    And also, you are creating an infinite loop because the condition

    while (startPtr < endPtr)
    

    will always be true.