문제 출처 : leetcode.com/problems/most-common-word/
문제 해석 : 차단된 단어를 제외하고 문장에서 가장 많이 나온 단어를 찾는 것이다.
문제 풀이 : 단어 이외에 다른 문자들도 섞여 있기 때문에 정규표현식을 이용해서 전처리를 진행한 후에 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 사이트에 있습니다. 혹시 문제가 되는 부분이 있으면 연락 바랍니다.
'📊알고리즘, 문제풀이 > 📈문제풀이 (PS)' 카테고리의 다른 글
[알고리즘][Python] LeetCode 5 Longest Palindromic Substring 문제 풀이 (0) | 2021.02.16 |
---|---|
[알고리즘][Python] LeetCode 49 Group Anagrams 문제 풀이 (0) | 2021.02.16 |
[알고리즘][Python] LeetCode 937 Reorder Data in Log Files 문제 풀이 (0) | 2021.02.15 |
[알고리즘][Python] LeetCode 344 Reverse String 문제 풀이 (0) | 2021.02.15 |
[알고리즘][Python] LeetCode 125 Valid Palindrome 문제 풀이 (0) | 2021.02.14 |