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.
Note that words can not contain punctuation symbols.
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"
Constraints:
1 <= paragraph.length <= 1000paragraph consists of English letters, space
' ', or one of the symbols:"!?',;.".0 <= banned.length <= 1001 <= banned[i].length <= 10banned[i]consists of only lowercase English letters.
819. Most Common Word
์ฃผ์ด์ง ๋ฌธ์ฅ(paragraph)๊ณผ ๊ธ์ง ๋จ์ด ๋ชฉ๋ก(banned)์ด ์ฃผ์ด์ง ๋,
๊ธ์ง๋์ง ์์ ๋จ์ด ์ค ๊ฐ์ฅ ๋ง์ด ๋ฑ์ฅํ ๋จ์ด๋ฅผ ์ฐพ๋ ๋ฌธ์
๋ฌธ์ ์์ ์ฃผ์ด์ง๋ ์ฃผ์ ์กฐ๊ฑด์ ๋ค์๊ณผ ๊ฐ๋ค.
๋์๋ฌธ์๋ฅผ ๊ตฌ๋ถํ์ง ์์
๋ฌธ์ฅ์๋ ๊ณต๋ฐฑ, ๋ง์นจํ, ์ผํ, ๋๋ํ ๋ฑ์ ๋ฌธ์ฅ๋ถํธ๊ฐ ํฌํจ๋จ
๋จ์ด๋ ์ํ๋ฒณ์ผ๋ก๋ง ๊ตฌ์ฑ๋จ
๋ฌธ์ฅ๋ถํธ๋ ๋จ์ด์ ์ธ์ ํด ์์ด๋ ๋ฌด์ํด์ผ ํจ
์ ๋ต์ ๋ฐ๋์ ํ๋๋ก ๋ณด์ฅ๋จ
๊ฒฐ๊ณผ๋ ์๋ฌธ์๋ก ๋ฐํํด์ผ ํจ
โํ์ด
import re
from collections import defaultdict
class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
word_count = defaultdict(int)
words = re.findall(r'[a-zA-Z]+', paragraph)
for word in words:
if word.lower() not in banned:
word_count[word.lower()] += 1
return max(word_count, key=word_count.get)
[a-zA-Z]+
โ ์์ด ์ํ๋ฒณ์ด 1๊ธ์ ์ด์ ์ฐ์๋ ๋ถ๋ถ๋ฌธ์ฅ๋ถํธ(
, . ! ? ' ;)์ ๊ณต๋ฐฑ ์๋ ์ ๊ฑฐ๊ฒฐ๊ณผ๋ ์์ด ๋จ์ด ๋ฆฌ์คํธ ํํ
dictionary์ key ์ค value(๋ฑ์ฅ ํ์)๊ฐ ๊ฐ์ฅ ํฐ key ๋ฐํ
๋ฌธ์ ์์ ์ ๋ต์ด ์ ์ผํจ์ด ๋ณด์ฅ๋๋ฏ๋ก ์ถ๊ฐ ์ฒ๋ฆฌ ๋ถํ์
๐กCounter ์ฌ์ฉ ํ์ด
import re
from collections import Counter
class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
banned_set = set(banned)
words = re.findall(r'[a-zA-Z]+', paragraph.lower())
counter = Counter(word for word in words if word not in banned_set)
return counter.most_common(1)[0][0]
Counter, set์ ์ฌ์ฉํ๋ฉด ๋ ํจ์จ์ ์ธ ํ์ด๊ฐ ๊ฐ๋ฅํ๋ค๊ณ ํจ
banned List๋ฅผ set์ผ๋ก ๋ฐ๊พผ๋ค -> not in ์ฐ์ฐ์ด O(1)์ด ๋จ
์ ๊ทํํ์์ผ๋ก ๋จ์ด๋ค๋ง ์๋ฌธ์๋ก ์ถ์ถํด์ words์ ์ ์ฅ
banned_set์ ์์ง ์์ ๋จ์ด๋ค์ Counter๋ก ์ธ๊ธฐ
most_common์ ์ ์ฒด
๋ฑ์ฅ ํ์๊ฐ ๋ง์ ์์๋๋ก ์ ๋ ฌ๋ ๊ฒฐ๊ณผ๋ฅผ ๋ฐํํ๋ ๋ฉ์๋
ํ์
counter.most_common(n)nโ ์์ ๋ช ๊ฐ๋ฅผ ๊ฐ์ ธ์ฌ์ง๋ฐํ๊ฐ โ
(์์, ํ์)ํํ์ ๋ฆฌ์คํธ
counter.most_common(1)[0][0]๋จ๊ณ๋ณ ํด์
most_common(1)
โ[('ball', 2)][0]
โ('ball', 2)[0]
โ'ball'
