5 lines in Java beat 95%


  • 0

    I've tried several ways to solve this problem, at last, I found one of the fastest solutions, which beats 94.83% right now.

        public boolean isAnagram(String s, String t) {
            int[] chars = new int['z'-'a'+1];
            for(char c: s.toCharArray()) {chars[c - 'a']++;}
            for(char c: t.toCharArray()) {chars[c - 'a']--;}
            for(int count: chars) { if(count != 0) {return false;}}
            return true;
        }
    

    since it doesn't check s & t, and it handle s & t as char[] (call the function twice), it is faster than other idea

    at the beginning, I used HashMap things to consider the extensibility, but it doesn't matter for this problem

        public boolean isAnagram(String s, String t) {
            if (s == null && t == null || s.length() == 0 && t.length() == 0) {return true;}
            if (s.length() != t.length()) {return false;}
            int len = s.length();
            char[] s_ = s.toCharArray(), t_ = t.toCharArray();
            HashMap<Character, Integer> hash = new HashMap<Character, Integer>();
            for (char c: s_) {
                if (hash.containsKey(c)) {
                    hash.put(c, hash.get(c) + 1);
                }
                else {hash.put(c, 1);}
            }
            for (char c: t_) {
                if (hash.containsKey(c)) {
                    if (hash.get(c) == 1) {hash.remove(c);}
                    else {hash.put(c, hash.get(c) - 1);}
                }
                else {return false;}
            }
            return hash.isEmpty();
        }
    

Log in to reply
 

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