개요
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;
};
'알고리즘' 카테고리의 다른 글
[알고리즘] LeetCode Majority Element JS (0) | 2022.12.05 |
---|---|
[알고리즘] LeetCode Reverse Linked List JS (0) | 2022.12.04 |
[알고리즘] LeetCode First Bad Version JS (0) | 2022.12.03 |
[알고리즘] LeetCode Linked List Cycle JS (0) | 2022.12.02 |
[알고리즘] LeetCode Balanced Binary Tree JS (0) | 2022.12.02 |