и посмотреть медиа
Kotlin | LeetCode
и посмотреть медиа
LeetCode problems and solutions in Kotlin.
LeetCode problems and solutions in Kotlin.
AI bot for text-to-speech and voice cloning in Telegram. Create audio using neural network quickly and easily.
LeetCode problem solutions in Kotlin. Optimized code for mobile developers and algorithm specialists.
Задача: 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 { fun mostCommonWord(paragraph: String, banned: List): String { val normalizedStr = paragraph.map { if (it.isLetterOrDigit()) it.lowercaseChar() else ' ' }.joinToString("") val words = normalizedStr.split("\\s+".toRegex()).filter { it.isNotEmpty() } val wordCount = mutableMapOf() val bannedWords = banned.toSet() for (word in words) { if (word !in bannedWords) { wordCount[word] = wordCount.getOrDefault(word, 0) + 1 } } return wordCount.maxByOrNull { it.value }!!.key } Ставь 👍 и забирай 📚 Базу знаний
Открыть канал и посмотреть медиаOnly registered users can share their opinion.
Be the first to share your impression of this resource!