Diary, Data, IT

[LeetCode] 819. Most Common Word - Python 본문

Coding Test/LeetCode

[LeetCode] 819. Most Common Word - Python

라딘 2023. 4. 11. 17:40

 

[LeetCode] 819. Most Common Word - Python

 

 

Most Common Word - LeetCode

Can you solve this real interview question? Most Common Word - Given a string paragraph and a string array of the banned words banned, return the most frequent word that is not banned. It is guaranteed there is at least one word that is not banned, and tha

leetcode.com

 

 

문제

특정 문단과 금지 단어의 배열이 주어지며, 금지되지 않은 가장 많이 등장한 단어를 반환하는 문제입니다.

문단의 단어는 대소문자를 구분하지 않으며, 답은 소문자로 반환되어야 합니다.

 

 

아이디어

리스트에 포함된 요소의 수를 세는 collections.Counter를 이용하면 문제를 쉽게 해결할 수 있다.

하지만 단어를 세기 전에 미리 불필요한 특수문자는 제거하고, 소문자로 변환해주는 등의 전처리가 필요하다.

또 단어를 센 결과에 금지된 단어(banned)가 포함되어 있다면 이는 제외하고, most_common 단어를 반환한다.

 

 

코드

class Solution:
    def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:

        import collections
        import re

        # 대소문자 구분을 하지 않고, 특수문자 무시
        paragraph2 = paragraph.lower()
        paragraph2 = re.sub('[^a-z0-9]', ' ', paragraph2)
        word = paragraph2.split(' ')

        result = collections.Counter(word)

        banned.append('')  #공백도 count에서 제거
        
        for ban in banned:
            if ban in result:
                del result[ban]

        return result.most_common(1)[0][0]