拿 "aab" 在 "abaac" 里从左往右移动一个三格的小框。第一框 "aba" 里有两个 a、一个 b,次序虽不同,数量一样,记下起点 0。框向右挪一步,左边的 a 走了、右边的 a 又进来,"baa" 也合格,记下 1。最后 "aac" 缺 b,就到此为止。
每次只进一个、出一个,没有必要重算整框。题目限定小写英文字母,两张 26 格的计数表就够用。
class Solution:
def findAnagrams(self, s: str, p: str) -> list[int]:
width = len(p)
if width > len(s):
return []
goal = [0] * 26
window = [0] * 26
for char in p:
goal[ord(char) - ord('a')] += 1
starts = []
for right, char in enumerate(s):
window[ord(char) - ord('a')] += 1
if right >= width:
window[ord(s[right - width]) - ord('a')] -= 1
if right + 1 >= width and window == goal:
starts.append(right - width + 1)
return starts
窗口有可能重叠,所以命中后仍然只往前挪一格。每次比较至多看 26 项,总时间 O(|p| + 26|s|),在固定字母表下是线性时间;除返回结果外空间 O(26)。

