Posted on 2023-02-04 17:28
Uriel 阅读(35)
评论(0) 编辑 收藏 引用 所属分类:
字符串处理 、
闲来无事重切Leet Code 、
游标.移动窗口
给出两个字符串s1和s2,问s1的某种排列是否是s2的子串,又一python Counter的应用,先用Counter计算s1各个字符的出现次数,然后用sliding window,s2出现在sliding window中的字符对应的Counter减1,然后判断是否存在某个sliding window让Counter中所有计数归零
1 #567
2 #Runtime: 299 ms (Beats 32.65%)
3 #Memory: 14 MB(Beats 23.38%)
4
5 class Solution(object):
6 def checkInclusion(self, s1, s2):
7 """
8 :type s1: str
9 :type s2: str
10 :rtype: bool
11 """
12 cnt_s1 = Counter(s1)
13 l1 = len(s1)
14 for i in range(len(s2)):
15 if s2[i] in cnt_s1:
16 cnt_s1[s2[i]] -= 1
17 if i >= l1 and s2[i-l1] in cnt_s1:
18 cnt_s1[s2[i-l1]] += 1
19 if all([cnt_s1[i] == 0 for i in cnt_s1]):
20 return True
21 return False