python method beat 99%


  • 0
    D

    class Solution(object):
    def findAnagrams(self, s, p):
    """
    :type s: str
    :type p: str
    :rtype: List[int]
    """
    d_s, d_p = {}, {}
    result = []

        for v in p:
            if v in d_p:
                d_p[v] += 1
            else:
                d_p[v] = 1
                
        n = len(p)
        for v in s[:n]:
            if v in d_s:
                d_s[v] += 1
            else:
                d_s[v] = 1
        if d_s == d_p:
            result.append(0)
    
        for i,v in enumerate(s[n:]):
            # del first
            if d_s[s[i]] == 1:
                del d_s[s[i]]
            else:
                d_s[s[i]] -= 1
            # add last 
            if v in d_s:
                d_s[v] += 1
            else:
                d_s[v] = 1
            # check if equal
            if d_s == d_p:
                result.append(i+1)
                
        return result

Log in to reply
 

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