StringIndexOutOfBoundsException Java


  • 0
    K

    public class Solution {

    static int index = 0;
    static int myLen = 1;
    
     void checkPali(String s, int c1, int c2) {
        int i = c1, j = c2, len = s.length();
        while (i >= 0 && j < len && s.charAt(i) == s.charAt(j)) {
            i--;
            j++;
        }
        if (j - i + 1 - 2 > myLen) {
            myLen = j - i - 2 + 1;
            index = c1;
        }
    
    }
    
     void checkPali(String s, int center) {
        int i = center, j = center, len = s.length();
        while (i >= 0 && j < len && s.charAt(i) == s.charAt(j)) {
            i--;
            j++;
        }
        if (j - i + 1 - 2 > myLen) {
            myLen = j - i - 2 + 1;
            index = center;
        }
    }
    
    public  String longestPalindrome(String s) {
        int len = s.length();
        for (int i = 0; i < len - 1; i++) {
            checkPali(s, i);
            if (s.charAt(i) == s.charAt(i + 1)) {
                checkPali(s, i, i + 1);
            }
        }
        int l = index - (myLen - 1) / 2;
        return s.substring(l, l+myLen);
    }
    

    }

    I am getting this exception Line 40: java.lang.StringIndexOutOfBoundsException: String index out of range: 9 for test case "aaabaaaa" but its running fine on my system. Can somebody tell me the reason?


  • 0
    K

    I think there is some problem in judge. I submit the same solution on lintcode and it got accepted.


  • 0

    Just remove the static keyword from your code, and it got Accepted. Please read the FAQ item no. 3 to understand why static/global variables cause problems like this.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.