Five line 12ms C++ solution using array for map (not unordered_map)


  • 0
    D

    Characters have a relatively small value range, so there's no real need for unordered_map. We can just use an array with 128 values for the character counts.

    class Solution {
    public:
        bool isAnagram(string s, string t) {
            array<int, 128> mp {};
            for (char c : s) { mp[c]++; }
            for (char c : t) { if (--mp[c] < 0) { return false; } }
            for (int i : mp) { if (i > 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.