본문 바로가기
알고리즘/LeetCode

[Leetcode][자바스크립트][Easy] 383. Ransom Note

by Benjamin_Choi 2022. 1. 10.

풀이

/**
 * 383_RansomNote.js
 * Easy
 * https://leetcode.com/problems/ransom-note/
 */

var canConstruct = function(ransomNote, magazine) {
    const mHash = {};
    magazine.split("").forEach((char) => {
        if (!mHash[char]) {
            mHash[char] = 1;
        } else {
            mHash[char]++;
        }
    });

    for (let i = 0; i < ransomNote.length; i++) {
        if (!mHash[ransomNote[i]]) return false;

        mHash[ransomNote[i]]--;
    }
        
    return true;
};

ransomNote 안의 모든 글자가 magazine 에 포함되는지 확인하는 문제다. magazine 을 전부 확인해서 hash 를 만들고, 해당 hash 를 기반으로 ransomNote 의 모든 글자를 확인해서 true/false 를 return 한다. 

 

 

댓글