438. Find All Anagrams in a String python

给定一个字符串s和一个非空字符串p,找出s中所有p的字符串的起始索引。

Input:
s: "cbaebabacd" p: "abc"
Output:
[0, 6]
Explanation:
The substring with start index = 0 is "cba", which is an anagram of "abc".

The substring with start index = 6 is "bac", which is an anagram of "abc".

class Solution(object):
    def findAnagrams(self, s, p):
        """
        :type s: str
        :type p: str
        :rtype: List[int]
        """
        ans = []
        scounter = collections.Counter()
        pcounter = collections.Counter(p)
        lens = len(s)
        lenp = len(p)
        for i in range(lens):
            scounter[s[i]] += 1
            if i >= lenp:
                scounter[s[i-lenp]] -= 1
                if scounter[s[i-lenp]] == 0:
                    del scounter[s[i-lenp]]
            if scounter == pcounter:
                ans.append(i - lenp + 1)
        return ans

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值