---
# System prepended metadata

title: 383. Ransom Note
tags: [JavaScript, Hash Map/Set, Easy, Grind 75]

---

思考:
字串1要可以被字串2組成
但有出現次數的問題 所以要用hash 不能用 set

```c++=
class Solution {
public:
    bool canConstruct(string ransomNote, string magazine) {
        unordered_map <char, int> hash;
        for(auto i : magazine){
            hash[i]++;
        }
        for(auto i : ransomNote){
            if(!hash[i]){
                return false;
            }else{
                hash[i]--;
            }
        }
        return true;
    }
};

```


```=
/**
 * @param {string} ransomNote
 * @param {string} magazine
 * @return {boolean}
 */
var canConstruct = function(ransomNote, magazine) {
    const hash = new Map();
    const hash2 = new Map();
    for(let i = 0; i < magazine.length; i++){
        hash.set(magazine[i], (hash.get(magazine[i]) || 0) + 1);
    }
    for(let i = 0; i < ransomNote.length; i++){
        hash2.set(ransomNote[i], (hash2.get(ransomNote[i]) || 0) + 1);
    }    
    console.log(hash);
    console.log(hash2);
    for(let i = 0; i < ransomNote.length; i++){
        if(hash2.get(ransomNote[i]) > (hash.get(ransomNote[i]) || 0)){
            return false;
        }
    }
    
    
    
    
    
    
    return true;
};

```


```=
/**
 * @param {string} ransomNote
 * @param {string} magazine
 * @return {boolean}
 */
var canConstruct = function(ransomNote, magazine) {
    const hash = new Map();

    // 遍歷 magazine，統計每個字符的數量
    for (let i = 0; i < magazine.length; i++) {
        hash.set(magazine[i], (hash.get(magazine[i]) || 0) + 1);
    }

    // 遍歷 ransomNote，減少對應字符的數量
    for (let i = 0; i < ransomNote.length; i++) {
        if (hash.get(ransomNote[i]) <= 0 || hash.get(ransomNote[i]) === undefined) {
            return false;
        } else {
            hash.set(ransomNote[i], hash.get(ransomNote[i]) - 1);
        }
    }

    return true;
};


```