함번보고 두번보고
[LeetCode] 819. Most Common Word 본문
- 문제
금지된 단어를 제외한 가장 흔하게 등장하는 단어를 출력하라. 대소문자 구분을 하지 않으며(case-insensitive), 구두점(마침표, 쉼표 등) 또한 무시한다.
- 입력
Input: paragraph = "Bob hit a ball, the hit BALL flew far after it was hit."
banned = ["hit"]
- 출력
"ball"
var mostCommonWord = function(paragraph, banned) {
//1. banned set 초기화
const bannedSet = new Set(banned);
//2. 입력값 소문자변환, 문자열 배열로 변환
const words = paragraph.toLowerCase().split(/\W+/);
//3. banned되지 않은 단어 중 가장 많이 나타나는 단어 count
const map = new Map();
for (const w of words) {
if (w === '') continue;
if (!bannedSet.has(w)) {
if (!map.has(w)) {
map.set(w, 1);
} else {
map.set(w, map.get(w)+1);
}
}
}
//4. 맵의 value 최대값 구하기
return [...map.entries()].reduce((a,b) => a[1] > b[1] ? a : b)[0];
};
'Algorithm' 카테고리의 다른 글
[LeetCode] 49. Group Anagrams (0) | 2021.03.20 |
---|
Comments