動機

雖然說是複習sliding window,但學到一個很迷的技巧

Problem

Given two strings s1 and s2, return true if s2 contains a permutation of s1, or false otherwise.

In other words, return true if one of s1's permutations is the substring of s2.

 

Example 1:

Input: s1 = ab, s2 = eidbaoooOutput: trueExplanation: s2 contains one permutation of s1 (ba).

Example 2:

Input: s1 = ab, s2 = eidboaooOutput: false

 

Constraints:

  • 1 <= s1.length, s2.length <= 104
  • s1 and s2 consist of lowercase English letters.

Sol

比對counter就好,但是substract會讓0留下來,會讓下次比對沒用

所以要用now += Counter()

class Solution:
    def checkInclusion(self, s1: str, s2: str) -> bool:
        target,a,b = Counter(s1),0,len(s1)
        
        now = Counter(s2[a:b-1])
        for b in range(len(s1),len(s2)+1):
            now.update(s2[b-1])
            #print(now,a,b)
            if now == target:
                return True
            else:
                now.subtract(s2[a])
                now += Counter() # remove all items whose val is 0
                a += 1
        return False