forked from atilsamancioglu/DA2-InterviewChallengeSolutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
findallanagramsinastring.py
39 lines (26 loc) · 1.12 KB
/
findallanagramsinastring.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
'''
Given two strings s and p, return an array of all the start indices of p's anagrams in s. You may return the answer in any order.
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
'''
class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
if len(p) > len(s):
return []
pDict = {}
sDict = {}
result = []
for i in range(len(p)):
pDict[p[i]] = 1 + pDict.get(p[i],0)
sDict[s[i]] = 1 + sDict.get(s[i],0)
if pDict == sDict:
result.append(0)
leftPointer = 0
for rightPointer in range(len(p),len(s)):
sDict[s[rightPointer]] = 1 + sDict.get(s[rightPointer],0)
sDict[s[leftPointer]] -= 1
if sDict[s[leftPointer]] == 0:
sDict.pop(s[leftPointer])
leftPointer += 1
if sDict == pDict:
result.append(leftPointer)
return result