438. 找到字符串中所有字母异位词 - 力扣(LeetCode)


python
from collections import Counter
class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
if len(s) < len(p):
return [] # s 比 p 还短,直接返回空列表
res = []
p_count = Counter(p) # 统计 p 中字符出现次数
s_count = Counter(s[:len(p)]) # 统计窗口内的字符出现次数
if s_count == p_count:
res.append(0) # 第一个窗口匹配
for i in range(len(p), len(s)):
s_count[s[i]] += 1 # 加入新的字符
s_count[s[i - len(p)]] -= 1 # 移除窗口左侧字符
if s_count[s[i - len(p)]] == 0:
del s_count[s[i - len(p)]] # 清理计数为 0 的字符
if s_count == p_count:
res.append(i - len(p) + 1) # 记录起始索引
return res