Check if Anagram using Hash Map


  • 0

    Pass 1 : Construct a lookup map for String 1 with character as key & count at # of occurrences
    Pass 2: For String 2 for every character that is present in lookup map decrement
    Step 3: Check if MapEntry count values are 0

    public class Solution {
        public boolean isAnagram(String s, String t) {
            if(s == null && t == null){
                return true;
            }
            if(s.isEmpty() && t.isEmpty()){
                return true;
            }
            if(s.length() != t.length()){
                return false;
            }
            Map<Character,Integer> m = new HashMap<>();
            for(Character c : s.toCharArray()){
                int count = m.containsKey(c) ? m.get(c) : 0;
                m.put(c, ++count);
            }
            for(Character c : t.toCharArray()){
                if(m.containsKey(c)){
                     int count = m.get(c);
                     m.put(c, --count);
                }
            }
            for(Map.Entry<Character,Integer> e : m.entrySet()){
                if(e.getValue() != 0){
                    return false;
                }
            }
            return true;
        }
    }
    

  • 0
    A

    @krunal.shah.neugmail.com You could've used unordered_multiset for a much cleaner code. You wouldn't have to manually increase/decrease the count of characters.

    bool isAnagram(string s, string t) {
            if(s.length()!=t.length())
                return false;
            unordered_multiset<char> ums;
            for(auto ch: s){
                ums.insert(ch);
            }
            for(auto ch: t){
                if(ums.find(ch) == ums.end()){
                    return false;
                }
                ums.erase(ums.find(ch));
            }
            ums.clear();
            return true;
        }
    

Log in to reply
 

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