문제 출처
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
문제 설명
금지된 단어를 제외한 가장 흔하게 등장하는 단어를 출력하라. 대소문자 구분을 하지 않으며, 구두점(마침표, 쉼표 등) 또한 무시한다.

문제 풀이
class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
lowers = paragraph.lower() # 입력 문자열을 소문자로 변경
lowers = lowers.replace(",", " ") # 특수 문자들을 대체한다.
lowers = lowers.replace(".", " ")
lowers = lowers.replace("!", " ")
lowers = lowers.replace("?", " ")
lowers = lowers.replace(";", " ")
lowers = lowers.replace("'", " ")
words = lowers.split() # 띄어쓰기 기준으로 나눠준다.
# word는 words에 있는 단어이며,
# word가 banned에 있는 단어가 아니고, 아무것도 안적힌 문자가 아닌 word들을 list에 추가
words = [word for word in words if word not in banned and word != '']
# Counter() 함수를 사용하여 words에 있는 갯수를 반환한다.
cnt_dic = Counter(words)
# Counter의 key, value쌍을 list형태로 저장
cnt_lst = list(cnt_dic.items())
# 정렬
sorted_lst = sorted(cnt_lst, key=lambda x: -x[1])
# 가장 앞에 있는 단어를 ans로
ans = sorted_lst[0][0]
return ans
'알고리즘' 카테고리의 다른 글
[알고리즘] 배열-두 수의 합 - Jungyu Ko (0) | 2022.04.23 |
---|---|
[알고리즘] 문자열 조작-그룹 애너그램 - Jungyu Ko (0) | 2022.03.20 |
[알고리즘] 문자열조작-로그파일 재정렬 - Jungyu Ko (0) | 2022.03.20 |
[알고리즘] 문자열조작-문자열 뒤집기 - Jungyu Ko (0) | 2022.03.20 |
[알고리즘] 문자열 조작-유효한 팰린드롬 - Jungyu Ko (0) | 2022.03.20 |