zl程序教程

您现在的位置是:首页 >  其它

当前栏目

438. 找到字符串中所有字母异位词

字符串 所有 找到 字母 异位
2023-09-14 09:01:25 时间

在这里插入图片描述
思路:一开始想的是求p的组合,然后遍历所有的长度为len(p)的子串是否在p的组合里就行啦,没想到这个组合非python自带 jj 补充如下

 from itertools import combinations, permutations

        list(permutations([1,2,3],2))         #列举排列结果[(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]

        list(combinations([1,2,3],2))        #列举组合结果[(1, 2), (1, 3), (2, 3)]

然后又想着直接求p的元素个数字典,然后遍历就完事,结果过了一部分测试用例,超时了。

class Solution:
    def findAnagrams(self, s: str, p: str) -> List[int]:
       
        def dic(s):
            '''
            求s中每个字母的个数字典
            '''
            dic = {}
            for i in s:
                if i not in dic:
                    dic[i] = 1
                else:
                    dic[i] += 1
            return dic
        p_dic = dic(p)
        lis = []
        for i in range(len(s)-len(p)+1):
            if dic(s[i:len(p)+i]) == p_dic:
                lis.append(i)

        return lis

反思超时的原因其实就是求字母个数又用O(n)
改进了一手,采用上一个题的思路
49. 字母异位词分组
判断排序后相等不相等就完事
结果A了。

class Solution:
    def findAnagrams(self, s: str, p: str) -> List[int]:
        p=sorted(p)
        lis = []
        for i in range(len(s)-len(p)+1):
            if sorted(s[i:len(p)+i]) == p:
                lis.append(i)

        return lis        

因为python的排序快一点