Why my code throws exception "ArrayIndexOutOfBounds"


  • 0

    The idea of my codes is:
    use extra array to record how many times a certain letter is appeared, and then check if this two array is the same.

    However,the code runs well when the input string is short, but it throw a exception named ArrayIndexOutOfBoundsException when the input string is very long.

    public class Solution {
        public boolean isAnagram(String s, String t) {
            int ss = s.length();
            int ts = t.length();
            if(ss!=ts) return false;
            else
                return Arrays.equals(helper(s,length),helper(t,length));
        }
        
        public int[] helper(String input, int length){
            int[] res = new int[26];
            Arrays.fill(res,0);
    
            for (int i=0;i<length;i++){
                char c = input.charAt(i);
                int temp = (int)c;
                res[temp-97]++;
            }
            return res;
        }
    }

  • 0

    when I modified the code the error has disappeared...but I still don't understand what caused the error...

    public class Solution {
        public boolean isAnagram(String s, String t) {
            if(s.length()!=t.length()) return false;
            else{
                int length = s.length();
                return Arrays.equals(helper(s,length),helper(t,length));
            }
        }
        
        public int[] helper(String input, int length){
            int[] res = new int[26];
            Arrays.fill(res,0);
    
            for (int i=0;i<length;i++){
                res[input.charAt(i)-'a']++;
            }
            
            return res;
        }
    }

Log in to reply
 

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