Home > Mobile >  Why String index out of range?
Why String index out of range?

Time:11-15

below is my code for Leetcode 9 Palindrome Number. It shows "String index out of range error" for line 8 when the testcase is 121. Can anyone tell me why this happened? Thanks!

class Solution {
    public boolean isPalindrome(int x) {
        String s = String.valueOf(x);
        int i = 0;
        int j = s.length()-1;
        
        while(i < j){
            if(s.charAt(i) != s.charAt(j)){  <------ line 8
                return false;
            }else{
                s = s.substring(i 1,j);
            }
        }return true;
    }
}

CodePudding user response:

In the while loop, j remains constant whereas your "s" is reducing 1 char each loop. Example:

s = "theString";
i =0;j = 8;
loop 1: s = "theString";
loop 2: s = "heString";

as you see, s.subString(0, 8) will return the above exception because "s" is only 7 characters.

  • Related