
😎풀이
banned
된 단어를 미리 Set에 추가한다.
paragraph
를 소문자로 변경한 후 영문 대소문자가 아닌 경우를 기준으로 나눈다.
.,';
등 다양한 기호를 제거한 정제 단어가 banned
인 상태인지 확인한다.
- 빈도를 저장하여 가장 많은 빈도를 갖는 단어를 반환한다.
function mostCommonWord(paragraph: string, banned: string[]): string {
const bannedSet = new Set<string>(banned)
const words = paragraph.toLowerCase().split(/\W+/gi)
const frequent = new Map<string, number>()
for(const word of words) {
if(!word) continue
const curWord = word.replaceAll(/[^a-zA-Z]/g, '')
if(bannedSet.has(curWord)) continue
frequent.set(curWord, (frequent.get(curWord) ?? 0) + 1)
}
let mostFrequentChar = ''
let mostFrequent = 0
for(const [key, value] of frequent) {
if(mostFrequent > value) continue
mostFrequentChar = key
mostFrequent = value
}
return mostFrequentChar
};