TGViewer
Python | LeetCode Python | LeetCode @easy_python_task · 9.02K subscribers
Post #1931 786
Задача: 819. Most Common Word
Сложность: easy

Дана строка paragraph и массив строк banned, представляющий запрещенные слова. Верните наиболее часто встречающееся слово, которое не запрещено. Гарантируется, что существует хотя бы одно слово, которое не запрещено, и что ответ является уникальным.

Слова в paragraph нечувствительны к регистру, и ответ должен быть возвращен в нижнем регистре.

Пример:
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.


👨‍💻 Алгоритм:

1⃣Заменяем всю пунктуацию пробелами и одновременно переводим каждую букву в нижний регистр. Это можно сделать и в два этапа, но здесь мы объединяем их в один этап.

2⃣Разбиваем полученный результат на слова, используя пробелы в качестве разделителей.

3⃣Затем итерируемся по словам, чтобы подсчитать количество появлений каждого уникального слова, исключая слова из списка запрещенных. С помощью хеш-таблицы {слово->количество} проходим по всем элементам, чтобы найти слово с наивысшей частотой.

😎 Решение:
class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
normalized_str = ''.join([c.lower() if c.isalnum() else ' ' for c in paragraph])
words = normalized_str.split()
word_count = defaultdict(int)
banned_words = set(banned)

for word in words:
if word not in banned_words:
word_count[word] += 1


Ставь 👍 и забирай 📚 Базу знаний
More from @easy_python_task
  1. Oct 15, 2026Задача: 1474. Delete N Nodes After M Nodes of a Linked List Сложность: easy Вам дано начал…
  2. Oct 15, 2026Post #2446
  3. Oct 14, 2026Задача: 977. Squares of a Sorted Array Сложность: easy Дан целочисленный массив nums, отсо…
  4. Oct 13, 2026Post #2444
  5. Oct 13, 2026Задача: 462. Minimum Moves to Equal Array Elements II Сложность: medium Дан массив целых ч…
  6. Oct 13, 2026Задача: 1056. Confusing Number Сложность: easy Запутанное число - это число, которое при п…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →