Always Be Wise

문자열 조작 : 가장 흔한 단어(리트코드 819번) 본문

알고리즘/리트코드

문자열 조작 : 가장 흔한 단어(리트코드 819번)

bewisesh91 2021. 12. 14. 22:07
728x90

▶ 문제 : https://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

##### 문제 #####
금지된 단어를 제외한 가장 흔하게 등장하는 단어를 출력하라.
대소문자 구분을 하지 않으며, 구두점(마침표, 쉼표 등) 또한 무시한다.

##### 입력 #####
paragraph = "Bob hit a ball, the hit BALL flew far after it was hit."
banned = ["hit"]

##### 출력 #####
"ball"

 

▶ 접근 방법

리스트 컴프리헨션과 Counter 객체를 사용하여 해결하였다.

입력값에는 대소문자가 섞여 있으며 쉼표 등 구두점이 존재한다.
정규식을 사용하여 처리할 수 있다.
\w는 단어 문자(Word Character)를 의미하며, ^은 not을 의미한다. 
따라서 re.sub(r'[^\w]', ' ', paragraph)의 의미는
단어 문자가 아닌 모든 문자를 공백으로 치환(Substitute)하는 역할을 한다.

 

▶ 풀이 코드

from typing import List
from collections import Counter
import re

paragraph = "Bob hit a ball, the hit BALL flew far after it was hit."
banned = ["hit"]

def most_common_word(string:str, banned: List[str]) -> str:
    words = [word for word in re.sub(r'[^\w]', ' ', paragraph).lower().split() if word not in banned]
    counts = Counter(words)
    return counts.most_common(1)[0][0]

print(most_common_word(paragraph, banned))

 

▶ 관련 링크

2021.12.14 - [알고리즘/리트코드] - 문자열 조작 : 유효한 팰린드롬(리트코드 125번)

2021.12.14 - [알고리즘/리트코드] - 문자열 조작 : 문자열 뒤집기(리트코드 344번)

2021.12.14 - [알고리즘/리트코드] - 문자열 조작 : 로그 파일 재정렬(리트코드 937번)

 

Comments