O(n) solution using hashmap


  • 0
    C
    class Solution {
    public:
        bool isAnagram(string s, string t) {
            
            if(s.size() != t.size())
            {
                return false;
            }
            
            int size  = (int)s.size();
            unordered_map<int, int> m;
            
            for(int i = 0; i < size; i++)
            {
                int j = s[i] - 'a';
                m[j] = m[j] + 1;
            }
            
            for(int i = 0; i < size; i++)
            {
                int j = t[i] - 'a';
                if(m[j] == 0)
                {
                    return false;
                }
                else
                {
                    m[j] = m[j] - 1;
                }
            }
            return true;
        }
    };

Log in to reply
 

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