HOT 100 › 索引 › B3 滑动窗口 Sliding Window
LC 438找到字符串中所有字母异位词Find All Anagrams in a String 中等
找出 s 中所有与 p 互为异位词的子串的起始下标。
思路 定长滑动窗口计数:窗口每次进出各一个字符,比较窗口计数与 p 的计数是否相等。时间 O(n·Σ)。
class Solution: def findAnagrams(self, s: str, p: str) -> List[int]: m, n = len(s), len(p) if m < n: return [] need = Counter(p) win = Counter(s[:n]) ans = [0] if win == need else [] for i in range(n, m): win[s[i]] += 1 win[s[i - n]] -= 1 if win[s[i - n]] == 0: del win[s[i - n]] if win == need: ans.append(i - n + 1) return ans