438. Find All Anagrams in a String python

Given a string s and a non-empty string p, find the starting indices of all p strings in s.

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]
        """
        years = []
        scounter = collections.Counter()
        pcounter = collections.Counter(p)
        lens = lens(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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324706604&siteId=291194637