Short, Quick & Clean C++ Solution

  • 0

    Create an unordered map to store the magazine characters, with a count of number of letters e.g. ('a', 3), ('c', 2) for acaacc and then for the ransomNote string, decrement the count (or frequency), for each of it's characters. If the count goes below zero, then the magazine does not contain the ransomNote character, so return false, else return true (if all counts are zero or more).

    Here is the algorithm:

        bool canConstruct(string ransomNote, string magazine) {
            unordered_map<char, int> myMap;
            for(int i=0; i<magazine.size(); ++i) myMap[magazine[i]]++;
            for(int i=0; i<ransomNote.size(); ++i) myMap[ransomNote[i]]--;
            for(auto it=myMap.begin(); it!=myMap.end(); ++it) if(it->second < 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.