1 题目描述
2 解题思路:滑动窗口:
因为不管排列怎么排,s1字符串中的各个字母的个数是不变的。所以我们可以先设定一个大小和s1一样的滑动窗口。然后对s1和滑动窗口扫到的s2部分进行排序。如果而这一样,就说明包含这样的排列
class Solution:
def checkInclusion(self, s1: str, s2: str) -> bool:
needs, window = defaultdict(int), defaultdict(int)
left, right = 0, 0
valid = 0
for i in s1:
needs[i] += 1
while right < len(s2):
c = s2[right]
right += 1
if c in needs:
window[c] += 1
if window[c] == needs[c]:
valid += 1
print(left, right)
while right - left >= len(s1):
if valid == len(needs):
return True
d = s2[left]
left += 1
if d in needs:
if window[d] == needs[d]:
valid -= 1
window[d] -= 1
return False