и посмотреть медиа
Java | LeetCode
и посмотреть медиа
LeetCode tasks and solutions in Java.
AI bot for text-to-speech and voice cloning in Telegram. Create audio using neural network quickly and easily.
LeetCode task solutions in Java with emphasis on clean code and optimization. Topics: arrays, trees, graphs, dynamic programming. Ideal for technical preparation.
Задача: 438. Find All Anagrams in a String Сложность: medium Даны две строки s и p, вернуть массив всех начальных индексов анаграмм строки p в строке s. Ответ можно вернуть в любом порядке. Анаграмма - это слово или фраза, образованные перестановкой букв другого слова или фразы, обычно с использованием всех исходных букв ровно один раз. Пример: Input: s = "cbaebabacd", p = "abc" Output: [0,6] Explanation: The substring with start index = 0 is "cba", which is an anagram of "abc". The substring with start index = 6 is "bac", which is an anagram of "abc". 👨💻 Алгоритм: 1⃣Построить эталонный счетчик pCount для строки p. 2⃣Передвигать скользящее окно по строке s: Пересчитывать счетчик скользящего окна sCount на каждом шаге, добавляя одну букву справа и удаляя одну букву слева. 3⃣Если sCount == pCount, обновить выходной список. Вернуть выходной список. 😎 Решение: class Solution { public List findAnagrams(String s, String p) { int ns = s.length(), np = p.length(); if (ns < np) return new ArrayList(); Map pCount = new HashMap(); Map sCount = new HashMap(); for (char ch : p.toCharArray()) { pCount.put(ch, pCount.getOrDefault(ch, 0) + 1); } List output = new ArrayList(); for (int i = 0; i < ns; ++i) { char ch = s.charAt(i); sCount.put(ch, sCount.getOrDefault(ch, 0) + 1); if (i >= np) { ch = s.charAt(i - np); if (sCount.get(ch) == 1) { sCount.remove(ch); } else { sCount.put(ch, sCount.get(ch) - 1); } } if (pCount.equals(sCount)) { output.add(i - np + 1); } } return output; } } Ставь 👍 и забирай 📚 Базу знаний
Открыть канал и посмотреть медиаOnly registered users can share their opinion.
Be the first to share your impression of this resource!