TGViewer
Java | LeetCode Java | LeetCode @easy_java_task · 6.43K subscribers
Post #1320 946
Задача: 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 {
public String mostCommonWord(String paragraph, List<String> banned) {
String normalizedStr = paragraph.replaceAll("[^a-zA-Z0-9 ]", " ").toLowerCase();
String[] words = normalizedStr.split("\\s+");
Map<String, Integer> wordCount = new HashMap<>();
Set<String> bannedWords = new HashSet<>(banned);

for (String word : words) {
if (!bannedWords.contains(word)) {
wordCount.put(word, wordCount.getOrDefault(word, 0) + 1);
}
}

return Collections.max(wordCount.entrySet(), Map.Entry.comparingByValue()).getKey();
}


Ставь 👍 и забирай 📚 Базу знаний
  • 👍 1
  • 💊 1
More from @easy_java_task
  1. Oct 17, 2026Задача: 745. Prefix and Suffix Search Сложность: hard Создайте специальный словарь, в кото…
  2. Oct 17, 2026Post #2303
  3. Oct 17, 2026Задача: 1431. Kids With the Greatest Number of Candies Сложность: easy Дано n детей с конф…
  4. Oct 16, 2026Задача: 735. Asteroid Collision Сложность: medium Нам дан массив asteroids, состоящий из ц…
  5. Oct 16, 2026Post #2300
  6. Oct 15, 2026Задача: 229. Majority Element II Сложность: medium Дан массив целых чисел размера n, найди…
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 →