TGViewer
Python | LeetCode Python | LeetCode @easy_python_task · 9.01K subscribers
Post #1855 789
Задача: 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:
def findAnagrams(self, s: str, p: str) -> List[int]:
ns, np = len(s), len(p)
if ns < np:
return []

pCount = Counter(p)
sCount = Counter()

output = []
for i in range(ns):
sCount[s[i]] += 1

if i >= np:
if sCount[s[i - np]] == 1:
del sCount[s[i - np]]
else:
sCount[s[i - np]] -= 1

if pCount == sCount:
output.append(i - np + 1)

return output


Ставь 👍 и забирай 📚 Базу знаний
  • 👍 1
More from @easy_python_task
  1. Oct 15, 2026Задача: 1043. Partition Array for Maximum Sum Сложность: medium Если задан целочисленный м…
  2. Oct 15, 2026Задача: 1474. Delete N Nodes After M Nodes of a Linked List Сложность: easy Вам дано начал…
  3. Oct 15, 2026Post #2446
  4. Oct 14, 2026Задача: 977. Squares of a Sorted Array Сложность: easy Дан целочисленный массив nums, отсо…
  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 →