Using HashMap, easy to understand


  • 0
    A

    This is my first post :)

       public boolean isAnagram(String s, String t) {
            HashMap<Character,Integer> map = new HashMap();
           //count occurance of every char in s
            for (char c : s.toCharArray()) {
                map.put(c,map.getOrDefault(c,0)+1);
            }
           //decrement occurance of matching char
            for (char c:t.toCharArray()) {
                map.put(c,map.getOrDefault(c,2)-1);
            }
           //if anything is left behind, its not an anagram
            for (char key:map.keySet()) {
                if (map.get(key)!=0)
                    return false;
            }
            return true;
        }
    

Log in to reply
 

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