819. Most Common Words

Seong-Soo Jeong·2021년 4월 9일
post-thumbnail

문제

문자열 paragraph와 금지된 단어들의 배열 banned 가 주어진다. banned에 포함되지 않은 단어 중, 가장 많이 사용된 단어를 반환하시오. 답은 유일하며, paragraph에는 banned에 포함되지 않은 적어도 하나의 단어가 존재하고 있다.

Example 1:

Input: paragraph = "Bob hit a ball, the hit BALL flew far after it was hit.", banned = ["hit"]
Output: "ball"
Explanation:
"hit" occurs 3 times, but it is a banned word.
"ball" occurs twice (and no other word does), so it is the most frequent non-banned word in the paragraph.
Note that words in the paragraph are not case sensitive,
that punctuation is ignored (even if adjacent to words, such as "ball,"),
and that "hit" isn't the answer even though it occurs more because it is banned.

Example 2:

Input: paragraph = "a.", banned = []
Output: "a"


풀이

문제의 핵심은 banned에 포함되지 않은 단어들의 갯수를 세는 방법이다.

Python에서는 dictionary의 한 종류인 Counter와 defaultdict를 제공하고 있으니, 이를 이용하면 쉽게 풀이할 수 있다.

하지만 여기서 조심할 것은 'Non-alphanumeric문자를 어떻게 걸러낼 것인가' 이다. 여기서는 paragraph의 모든 문자열을 순회하며, Non-alphanumeric문자를 ' '로 대치하는 방법을 사용할 것이다.

이를 Python으로 구현하면 다음과 같다.

1. Counter를 이용한 풀이.

from collections import Counter

class Solution:
    def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
        word_list = []
        
        # Non-alphanumeric문자를 ' '로 대치
        for char in paragraph:
            if not char.isalnum():
                paragraph = paragraph.replace(char, ' ')

	# paragraph의 모든 문자들을 소문자로 변환.
        paragraph = paragraph.lower()

	#banned에 포함되지 않은 단어들을 list에 삽입.
        for word in paragraph.split():
            if word not in banned:
                word_list.append(word)
		
        # list를 Counter로 변환.
        word_counter = Counter(word_list)

	#가장 많이 사용된 단어 반환.
        return word_counter.most_common(1)[0][0]

2. defaultdict를 이용한 풀이.

from collections import defaultdict

class Solution:
    def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
        word_dict = defaultdict(int)
        
        # Non-alphanumeric문자를 ' '로 대치
        for char in paragraph:
            if not char.isalnum():
                paragraph = paragraph.replace(char, ' ')

	# paragraph의 모든 문자들을 소문자로 변환.
        paragraph = paragraph.lower()

	# banned에 포함되지 않은 문자를 key로 개수를 value로 하는 defaultdict 생성.
        for word in paragraph.split():
            if word not in banned:
                word_dict[word] += 1
	
    # defaultdict를 정렬하여 가장 많이 사용된 단어를 반환.
        return sorted(word_dict.items(), key=lambda x: x[1], reverse=True)[0][0]
profile
Man in the middle

0개의 댓글