819. 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.
참고
You can read the full description here.
Solution
Approach
- Delete other characters except for alnum+underscore with
re.sub
. - List Comprehension makes code simple.
Implementation
import collections
import re
from typing import List
class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
words = [word for word in re.sub(r'[^\w]', ' ', paragraph)
.lower().split()
if word not in banned]
counts = collections.Counter(words)
# print(counts.most_common(1)) -> [('ball',2)]
return counts.most_common(1)[0][0]
Complexity Analysis
- : length of
paragraph
, : length ofbanned
- Time Complexity:
- Space Complexity: