본문 바로가기
Data Structure & Algorithms/Hasing

[Hashing] 383. Ransom Note

by 담백로봇 2023. 1. 6.

출처: leetcode

 

Given two strings ransomNote and magazine, return true if ransomNote can be constructed by using the letters from magazine and false otherwise.

Each letter in magazine can only be used once in ransomNote.

 

Example 1:

Input: ransomNote = "a", magazine = "b"
Output: false

Example 2:

Input: ransomNote = "aa", magazine = "ab"
Output: false

Example 3:

Input: ransomNote = "aa", magazine = "aab"
Output: true

 

Constraints:

  • 1 <= ransomNote.length, magazine.length <= 105
  • ransomNote and magazine consist of lowercase English letters.

 

내솔루션. 실제 답지는 왜이리 복잡하게 했는지

class Solution {
public:
    bool canConstruct(string ransomNote, string magazine) {
        
        unordered_map<char, int> ransom_hash;
        unordered_map<char, int> magazine_hash;
        
        for(char &i : ransomNote){
            ransom_hash[i]++;
        }
        
        for(char &i : magazine){
            magazine_hash[i]++;
        }
   
        
         for(auto &[key,val]: ransom_hash){ // find the other hash's key.

             if(magazine_hash.find(key) !=magazine_hash.end() ){
              magazine_hash[key] -= ransom_hash[key];
             }
            else{
                return false;
            }
         }

        for(auto &[key,val] : magazine_hash){
            if(val < 0){
                return false;
            }
        }
        return true;
    }
};

댓글