Easy to understand O(N) C++ hash table solution


  • 0
    H
    class Solution {
    public:
    bool canConstruct(string ransomNote, string magazine) {
        unordered_map<char, int> lettercount; // initialize hash map to create a count for letters available in magainze
        //add the letters from magazine to hash map
        for (char c:magazine){
            lettercount[c]++;
        }
        //subtract each letter from the necessary list of chars from ransomNote
        //we cannot create a ransom note if there is a letter that does not belong in the magazine, but needed for the note
        for (char c:ransomNote){
            lettercount[c]--;
            if (lettercount[c] == -1) return false;
        }
        return true;
    }
    

    };


Log in to reply
 

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