📊알고리즘, 문제풀이/📈문제풀이 (PS)

[알고리즘][Python] LeetCode 819 Most Common Word 문제 풀이

Written by Donghak Park

문제 출처 : leetcode.com/problems/most-common-word/

 

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


문제 해석 : 차단된 단어를 제외하고 문장에서 가장 많이 나온 단어를 찾는 것이다.

 

문제 풀이 : 단어 이외에 다른 문자들도 섞여 있기 때문에 정규표현식을 이용해서 전처리를 진행한 후에 Counter를 사용해서 이를 해결 하면 된다.


풀이 코드

from typing import List
import re
from collections import Counter


class Solution:
    def mostCommonWord(self, paragraph: str, banned : List[str]) -> str:
        
        para_list = [s for s in re.sub(r'[^\w]', ' ', paragraph).lower().split()
                     if s not in banned]

        counts = Counter(para_list)
        answer = counts.most_common(1)[0][0]
        return answer


if __name__=="__main__":
    paragraph = "Bob hit a ball, the hit BALL flew far after it was hit."
    banned = ["hit"]
    solution = Solution()
    print(solution.mostCommonWord(paragraph, banned))

author : donghak park
contact : donghark03@naver.com

## 문제의 저작권은 LeetCode 사이트에 있습니다. 혹시 문제가 되는 부분이 있으면 연락 바랍니다.