개요

ransomNote라는 문자열과 magazine이라는 문자열이 주어지는데 이때 ransomNote가 magazine에 포함되어있는지를 확인해보는 문제이다.

 

Ransom Note - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

 

풀이

단순히 includes로 돌려볼 수도 있겠지만 그렇게한다면 ransomNote가 따로 떨어져있을 경우를 찾지 못한다.

따라서 HashMap을 사용하였고 쉽게 풀어낼 수 있었다

/**
 * @param {string} ransomNote
 * @param {string} magazine
 * @return {boolean}
 */
var canConstruct = function (ransomNote, magazine) {
  const map = new Map();
  for (const char of ransomNote) map.set(char, (map.get(char) || 0) + 1);

  for (const char of magazine) {
    const count = map.get(char);
    if (count === undefined) continue;
    if (count === 1) map.delete(char);
    else map.set(char, count - 1);
  }

  return map.size === 0;
};
복사했습니다!