python - find all anagrams


  • 0
    S
    from collections import Counter
    class Solution(object):
        def findAnagrams(self, s, p):
            """
            :type s: str
            :type p: str
            :rtype: List[int]
            """
            
            if not (p or s):
                return []
            
            plen, slen = len(p), len(s)
            pcount, scount = Counter(p), Counter(s[0:plen])
            answer, d = [], dict(scount)
            for i in range(slen-plen+1):
                if i > 0:
                    d[s[i+plen-1]] = d.get(s[i+plen-1], 0) + 1
                    scount = Counter(d)
                    
                if scount == pcount:
                    answer.append(i)
                                
                d[s[i]] = d.get(s[i], 0) - 1
                if d[s[i]] == 0:
                    del d[s[i]]
            return answer
                    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.