Skip to content

Commit 73fc21c

Browse files
committed
may1899992020
1 parent f3310dc commit 73fc21c

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
class Solution:
2+
def findAnagrams(self, s: str, p: str) -> List[int]:
3+
# store results in list
4+
indices = []
5+
# store lenth of string p since this is reused multiple times
6+
length_p = len(p)
7+
8+
# check if p is longer than s, if yes, return empty list
9+
if length_p > len(s):
10+
return []
11+
12+
# create baseline for p by counting the characters in p (26 possible characters)
13+
# (similar to storing the counts in a dictionary)
14+
counter_p = [0] * 26
15+
for c in p:
16+
# convert each character to its index by calculating the int value and subtracting 97
17+
# a = 97 -> a-97 = 0
18+
# b = 98 -> b-97 = 1
19+
# etc.
20+
counter_p[ord(c) - 97] += 1
21+
22+
# initialize counter with the first characters
23+
counter = [0] * 26
24+
for i in range(length_p - 1):
25+
counter[ord(s[i]) - 97] += 1
26+
27+
# enumerate through remaining characters and compare to baseline (counter_p)
28+
# use enumerator to get both the index we need for removing the first character and
29+
# the character we want to add (we are starting with the first character after the once
30+
# that were initialized above (if len(p)=3, we start at the 3rd character)
31+
for i, c in enumerate(s[length_p - 1:]):
32+
# add current character
33+
counter[ord(c) - 97] += 1
34+
# compare to baseline
35+
if counter_p == counter:
36+
indices.append(i)
37+
# remove character
38+
counter[ord(s[i]) - 97] -= 1
39+
40+
return indices

0 commit comments

Comments
 (0)