链接:438. 找到字符串中所有字母异位词 - 力扣(LeetCode)

python里可以用==来判断list是否相等,list初始化定义可以用[0]*26

每往后一格,记录s串的list只要变两格即可,不用再重新遍历一遍

 1 class Solution(object):
 2     def findAnagrams(self, s, p):
 3         """
 4         :type s: str
 5         :type p: str
 6         :rtype: List[int]
 7         """
 8         len_s = len(s)
 9         len_p = len(p)
10         if len_p > len_s:
11             return []
12         i = 0
13         s_count = [0]*26
14         p_count = [0]*26
15         while i < len_p:
16             p_count[ord(p[i])-ord('a')] += 1
17             s_count[ord(s[i])-ord('a')] += 1
18             i += 1
19         res_list = []
20         if p_count == s_count:
21             res_list.append(0)
22         i = 1
23         j = len_p
24         while i <= (len_s-len_p):
25             s_count[ord(s[i-1])-ord('a')] -= 1
26             s_count[ord(s[j])-ord('a')] += 1
27             if p_count == s_count:
28                 res_list.append(i) 
29             i += 1
30             j += 1
31         return res_list
32 
33 
34