😎풀이

  1. banned된 단어를 미리 Set에 추가한다.
  2. paragraph를 소문자로 변경한 후 영문 대소문자가 아닌 경우를 기준으로 나눈다.
  3. .,';등 다양한 기호를 제거한 정제 단어가 banned인 상태인지 확인한다.
  4. 빈도를 저장하여 가장 많은 빈도를 갖는 단어를 반환한다.
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
};
profile
내 지식을 공유할 수 있는 대담함

0개의 댓글

Powered by GraphCDN, the GraphQL CDN