My Java Code: 5ms. VERBOSE but EASY to understand.


  • 0
    K

    This is not a well-optimized version!

        public boolean isAnagram(String s, String t) {
            if (s.isEmpty()&&t.isEmpty()) return true;
            int ls = s.length(), lt = t.length();
            if (ls != lt) return false;
            char[] str1 = s.toCharArray();
            char[] str2 = t.toCharArray();
            int[] freq1 = new int[26];
            int[] freq2 = new int[26];
            int count = 0, unique = 0;
            for (int i = 0; i < ls; i++) {
                freq1[str1[i] - 'a']++;
            }
            for (int i = 0; i < ls; i++) {
                freq2[str2[i] - 'a']++;
            }
            for (int i = 0; i < 26; i++) {
                if (freq1[i] != 0) unique++;
                if (freq1[i] == freq2[i]&&freq1[i] * freq2[i] > 0) count ++;
            }
            return count == unique;
        }
    

Log in to reply
 

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