[LeetCode Python3]567. Permutation in String

Python3 Solution:

from collections import defaultdict
class Solution:
    def checkInclusion(self, s1: str, s2: str) -> bool:
        need = defaultdict(int)
        window = defaultdict(int)
        for ch in s1:
            need[ch] += 1
        
        left, right = 0, 0
        valid = 0
        
        while right < len(s2):
            ch = s2[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(s1):
                    return True
                ch = s2[left]
                left += 1
                if ch in need:
                    if need[ch] == window[ch]:
                        valid -= 1
                    window[ch] -= 1
        return False

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