438. Find All Anagrams in a String

基本上是 Sliding window

class Solution:
    def findAnagrams(self, s: str, p: str) -> List[int]:
        freqS, freqP= [0 for _ in range(26)], [0 for _ in range(26)]
        res = []
        for ch in p:
            freqP[ord(ch)-97] += 1
        for i in range(len(s)):
            if i >= len(p):
                freqS[ord(s[i-len(p)])-97] -= 1
            freqS[ord(s[i])-97] += 1
            if freqS == freqP:
                # print("Get anagrams:", s[i-len(p)+1:i+1])
                res.append(i+1-len(p))
                
        return res

Last updated

Was this helpful?