새오의 개발 기록

Leetcode 819: 가장 흔한 단어 본문

Algorithm/Leetcode

Leetcode 819: 가장 흔한 단어

새오: 2022. 10. 1. 23:42

 

금지된 단어를 제외한 가장 흔하게 등장하는 단어를 출력하라.
대소문자 구분을 하지 않으며, 구두점(마침표, 쉼표 등 또한 무시한다.)



 

Most Common Word - 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

// 입력 예제
paragraph = "Bob hit a ball, the hit BALL flew far after it was hit."

// 출력 예제
"ball"

 

 

 

풀이

 

1. 정규 표현식, filter, Counter

 

def mostCommonWord(self, paragraph, banned):
    # 정규 표현식을 통해 단어가 아닌 것들을 전부 빈칸으로 바꿔줌
    # 소문자로 변경
    # 배열로 
    words = re.sub('[^\w]', ' ', paragraph).lower().split()
    # banned 배열 안에 있는 건 안 들어가도록
    words = filter(lambda x: x not in banned, words)
    # counter 자료구조 사용
    counter = collections.Counter(words)
    # Counter({u'ball': 2, u'a': 1, u'far': 1, u'after': 1 ..})

    # 가장 빈도 높은 값 
    return counter.most_common(1)[0][0]

 

 

'Algorithm > Leetcode' 카테고리의 다른 글

Leetcode 1: 두 수의 합  (0) 2022.10.03
Leetcode 49: 그룹 애너그램  (0) 2022.10.02
Leetcode 937: 로그 파일 재정렬  (0) 2022.10.01
Leetcode 125: 유효한 팰린드롬  (0) 2022.09.30
Leetcode 344: 문자열 뒤집기  (1) 2022.09.30