Algorithm/1일 1코테
[leetcode] 819. Most Common Word
대인보우
2021. 4. 28. 14:21
반응형
819. Most Common Word
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
조건
1. 금지어는 제거할 것
2. 특수문자 제거할 것
3. 소문자 혹은 대문자로 통일할 것
나의 답
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
import re
# 전처리
paragraph = re.sub("[!?',;.]", ' ', paragraph) # 특수문자 제거
paragraph = paragraph.lower() # 소문자로 통일
p = list(paragraph.split()) # 공백 기준으로 리스트로 분리
# 금지어 제거
answer = []
if banned:
for word in p:
if word not in banned: # 금지어에 없으면 append
answer.append(word)
else:
answer = p
# 빈도 넣을 리스트
cnt = list(answer.count(i) for i in answer)
# 문자와 빈도 결합
m = zip(answer, cnt)
# count 순으로 정렬하되 count가 같을 경우 abc순
m = sorted(m, key=lambda x : (-x[1], x[0]))
return m[0][0]
모범 답
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
import re
# 특수문자 제거, 소문자 통일, 공백으로 분리한 뒤
# banned 단어가 아니면 해당 word들을 list로 만듦.
words = [word for word in re.sub(r'[^\w]', ' ', paragraph).lower().split() if word not in banned]
# 단어 카운트 함수
counts = collections.Counter(words)
return counts.most_common(1)[0][0]
반응형