1 minute read

819. Most Common Word

문제 링크

https://leetcode.com/problems/most-common-word/description/

문제 설명

Given a string paragraph and a string array of the banned words banned, return the most frequent word that is not banned. It is guaranteed there is at least one word that is not banned, and that the answer is unique.

The words in paragraph are case-insensitive and the answer should be returned in lowercase.

제한사항

  • 1 <= paragraph.length <= 1000
  • paragraph consists of English letters, space ‘ ‘, or one of the symbols: “!?’,;.”.
  • 0 <= banned.length <= 100
  • 1 <= banned[i].length <= 10
  • banned[i] consists of only lowercase English letters.

입출력 예 #1

  1. Input: paragraph = “Bob hit a ball, the hit BALL flew far after it was hit.”, banned = [“hit”]
  2. Output: “ball”
  3. 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.

입출력 예 #2

  1. Input: paragraph = “a.”, banned = []
  2. Output: “a”

문제 풀이

  1. re.sub() 함수로 문자만 선택 및 문자열의 단어들을 소문자 정렬, banned에 있는 단어를 제외하여 취합
  2. Counter 함수의 most_common 객체를 이용하여 가장 흔한 단어 리턴
class Solution:
    def mostCommonWord(self, paragraph : str, banned : List[str]) -> str :
        words = [word for word in re.sub('[^\w]', ' ', paragraph).lower().split() if word not in banned]
        
        return Counter(words).most_common(1)[0][0]

Comments