Java Anagrams

  • + 5 comments

    Great explanation!

    But I believe you can still optimize it a little bit. How about using char array instead of charAt() function? Because every call to charAt() method contains internall check for ArrayOutOfBoundException.

    My vision:

    static boolean isAnagram(String a, String b) {
            if ((a == null || b == null) || (a.length() != b.length())) {
                return false;
            }
            final char[] ARRAY_A = a.toUpperCase().toCharArray();
            final Map<Character, Integer> map = new HashMap<>();
            for (int i = 0; i < ARRAY_A.length; i ++) {
                if (map.containsKey(ARRAY_A[i])) {
                    map.put(ARRAY_A[i], (map.get(ARRAY_A[i]) + 1));
                } else {
                    map.put(ARRAY_A[i], 1);
                }
            }
            final char[] ARRAY_B = b.toUpperCase().toCharArray();
            for (int i = 0; i < ARRAY_A.length; i ++) {
                if (map.containsKey(ARRAY_B[i])) {
                    Integer count = map.get(ARRAY_B[i]);
                    if (count == 0) {
                        return false;
                    } else {
                        count --;
                        map.put(ARRAY_B[i], count);
                    }
                } else {
                    return false;
                }
            }
            return true;
        }