python solution : sliding window


  • 0

    windows {p[x]}

    import collections
    class Solution(object):
    	def findAnagrams(self, s, p):
    
    		res=[]
    		cnt=collections.Counter(p)
    		matchN=len(p)
    		for idx,c in enumerate(s):
    			#front                  X[ ]
    			if idx-len(p) >=0:
    				cnt[s[idx-len(p)]]+=1
    				if cnt[s[idx-len(p) ]]>0:
    					matchN+=1
    			#find pattern       [ X]
    			if cnt[c]>0:				
    				matchN-=1
    
    			cnt[c]-=1
    			if matchN==0:
    				res.append(idx-len(p)+1)
    		return res
    

Log in to reply
 

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