Add optimal solution for 438
This commit is contained in:
parent
891689d0a9
commit
8689c3ab9d
1 changed files with 88 additions and 0 deletions
|
|
@ -0,0 +1,88 @@
|
|||
from typing import List, Optional
|
||||
from collections import defaultdict
|
||||
|
||||
class Solution:
|
||||
def findAnagrams(self, s: str, p: str):
|
||||
"""
|
||||
Основная идея:
|
||||
1 - подсчитать кол-во символов в подстроке p и использовать эти цифры как дельту до нехватающей анаграммы.
|
||||
"""
|
||||
res = []
|
||||
p_len = len(p)
|
||||
if p_len > len(s):
|
||||
return []
|
||||
p_count = defaultdict(int)
|
||||
for c in p:
|
||||
p_count[c] += 1
|
||||
i = 0
|
||||
# Парсим первый отрезок, чтобы встать в нулевую точку
|
||||
while i < p_len:
|
||||
p_count[s[i]] -= 1
|
||||
if p_count[s[i]] == 0:
|
||||
del p_count[s[i]]
|
||||
i += 1
|
||||
# Проверяем длину p_count
|
||||
if len(p_count) == 0:
|
||||
res.append(0)
|
||||
# Как только мы "встали" на первый отрезок строки, начинаем итерироваться далее, пока
|
||||
# не дойдем до конца.
|
||||
# Встаем опять на первый символ s чтобы начать идти дальше по ней
|
||||
i = 1
|
||||
j = len(p)
|
||||
#
|
||||
"""
|
||||
s = "abab", len(s) = 4
|
||||
p = "ab" len(p) = 2
|
||||
Следовательно закончить итерацию мы должны на i == 2, что равно 4 - 2
|
||||
"""
|
||||
while i <= (len(s) - len(p)):
|
||||
p_count[s[i-1]] += 1
|
||||
if p_count.get(s[i-1]) == 0:
|
||||
del p_count[s[i-1]]
|
||||
p_count[s[j]] -= 1
|
||||
if p_count.get(s[j]) == 0:
|
||||
del p_count[s[j]]
|
||||
print(p_count)
|
||||
print(len(p_count))
|
||||
if len(p_count) == 0:
|
||||
res.append(i)
|
||||
i += 1
|
||||
j += 1
|
||||
print(f"--i=={i},j={j}--")
|
||||
"""
|
||||
Последняя итерация
|
||||
i = 1, s[i] = b, s = "abab"
|
||||
0123
|
||||
ij
|
||||
p_count = {
|
||||
}
|
||||
|
||||
Добавляем к p_count выбывший символ s[i - 1] = "c"
|
||||
p_count = {
|
||||
c : 1
|
||||
}
|
||||
Проверям p_count["c"] на == 0 => no => continue
|
||||
|
||||
Вычитаем новый вошедший символ s[j] = "e"
|
||||
p_count = {
|
||||
c : 1
|
||||
e : 1
|
||||
}
|
||||
Проверям p_count["e"] на == 0 => no => continue
|
||||
|
||||
Проверяем len(p_count) == 0 -> no -> continue
|
||||
"""
|
||||
return res
|
||||
|
||||
c = Solution()
|
||||
# s = "cbaebabacd"
|
||||
# p = "abc"
|
||||
# print(c.findAnagrams(s, p))
|
||||
#
|
||||
# s = "af"
|
||||
# p = "be"
|
||||
# print(c.findAnagrams(s, p))
|
||||
|
||||
s = "abab"
|
||||
p = "ab"
|
||||
print(c.findAnagrams(s, p))
|
||||
Loading…
Reference in a new issue