C++ easy solution using unordered_map


  • 1
    J

    As you can see, using an unordered_map to store the number of char in the magazine.

    class Solution {
        unordered_map<char, int> count;
    public:
        bool canConstruct(string ransomNote, string magazine) {
            if(ransomNote.empty())
                return true;
            if(magazine.empty())
                return false;
            for(auto c: magazine)
                count[c]++;
            for(auto c: ransomNote) {
                if(count.find(c) == count.end() || count[c] == 0)
                    return false;
                count[c]--;
            }
            return true;
        }
    };
    

Log in to reply
 

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