链接: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         

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/958946.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!