[LeetCode Python3]438. Find All Anagrams in a String

Python3 Solution:

from collections import defaultdict
class Solution:
    def findAnagrams(self, s: str, p: str) -> List[int]:
        need = defaultdict(int)
        window = defaultdict(int)
        for ch in p:
            need[ch] += 1
        
        left, right = 0, 0
        valid = 0
        
        res = []
        while right < len(s):
            ch = s[right]
            right += 1
            
            if ch in need:
                window[ch] += 1
                if need[ch] == window[ch]:
                    valid += 1
                    
            while valid == len(need):
                if (right - left) == len(p):
                    res.append(left)
                ch = s[left]
                left += 1
                if ch in need:
                    if need[ch] == window[ch]:
                        valid -= 1
                    window[ch] -= 1
        return res

你可能感兴趣的:(LeetCode每日一题)