Hash Tables: Ransom Note

  • + 0 comments

    My soln. in C++

    void checkMagazine(vector magazine, vector note) {

    unordered_map<string, int> wordsMap;
    
    for (const string& word : magazine){
    
        if (wordsMap.find(word) == wordsMap.end()) { //key not in map
            //create new entry
            wordsMap[word] = 1;
    
        } else {
            //increment entry
            wordsMap[word]++;
        }
    }
    
    for (const string& word : note) {
        //if word is not in map or count = 0, fail
        if (wordsMap.find(word) == wordsMap.end() || wordsMap[word] == 0) {
    
            std::cout << "No" << std::endl;
            return;
        } else { //else, continue and decrement entry
    
            wordsMap[word]--;
        }
    
    }
    std::cout << "Yes" << std::endl;
    

    }