給出兩個(gè)字符串s1和s2,問s1的某種排列是否是s2的子串,又一python Counter的應(yīng)用,先用Counter計(jì)算s1各個(gè)字符的出現(xiàn)次數(shù),然后用sliding window,s2出現(xiàn)在sliding window中的字符對應(yīng)的Counter減1,然后判斷是否存在某個(gè)sliding window讓Counter中所有計(jì)數(shù)歸零
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