- categories: Code, Interview Question, leetcode, Easy
- source: https://leetcode.com/problems/most-common-word/description
- topics: Hash Table
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.
import re
class Solution(object):
def mostCommonWord(self, paragraph, banned):
"""
:type paragraph: str
:type banned: List[str]
:rtype: str
"""
paragraph = paragraph.lower()
words_dict = {}
words = [w for w in re.split(r"[!?',;. ]+", paragraph) if w and w not in banned]
for w in words:
words_dict[w] = words_dict.get(w, 0) + 1
return max(words_dict, key=words_dict.get)