목차
문제
- https://leetcode.com/problems/most-common-word/description/
- Runtime: 43ms, Memory 16.57MB
- 주어진 문자열(paragraph)에서 주어진 리스트(banned)에 없는 단어 중 가장 많이 등장하는 단어 반환
내 풀이
import collections
import re
class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
# 문자열과 띄어쓰기를 제외하고, 띄어쓰기로 변경
paragraph = re.sub("[^a-z ]", " ", paragraph.lower())
# 빈도 수를 계산
commons = collections.Counter(paragraph.split()).most_common()
# 빈도 수가 큰 순서대로 정렬
commons.sort(key=lambda x: -x[1])
# 빈도 수가 큰 순서대로 banned에 없다면 해당 값 반환
for common in commons:
if common[0] not in banned:
return common[0]반응형
'Problem Solving > LeetCode' 카테고리의 다른 글
| [LeetCode > Medium > 5] Longest Palindromic Substring (0) | 2024.06.09 |
|---|---|
| [LeetCode > Medium > 49] Group Anagrams (0) | 2024.06.09 |
| [LeetCode > Medium > 937] Reorder Data in Log Files (0) | 2024.06.09 |
| [LeetCode > Easy > 344] Reverse String (0) | 2024.06.09 |
| [LeetCode > Easy > 125] Valid Palindrome (0) | 2024.06.06 |