时间复杂度(O(n),思想:动态规划
class Solution:
def findAnagrams(self, s: str, p: str) -> []:
p_len = len(p)
p_dict = {}
r_dict = {}
positions = []
for index1, ch1 in enumerate(p):
if ch1 not in p_dict: p_dict[ch1] = 1
else: p_dict[ch1] += 1
for index, ch in enumerate(s):
if ch not in r_dict : r_dict[ch] = 1
else: r_dict[ch] += 1
if index >= p_len - 1:
if r_dict == p_dict:positions.append(index - p_len + 1)
first_ch = s[index - p_len + 1]
if r_dict[first_ch] == 1: r_dict.pop(first_ch)
else:r_dict[first_ch] -= 1
return positions