Skip to content

Commit e0c24ce

Browse files
committed
438
1 parent 3174311 commit e0c24ce

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

439-find_all_anagrams_in_a_string.py

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
"""
2+
https://leetcode.com/problems/find-all-anagrams-in-a-string/
3+
4+
(Is pretty similar to 567. Permutation in String)
5+
6+
Strat:
7+
Sliding window. See explaination from 567.
8+
9+
Stats: O(s + p) time, O(1) space -- one pass in both arrays + storing up to 26 letters in each array
10+
Runtime: 80 ms, faster than 94.67% of Python online submissions for Find All Anagrams in a String.
11+
Memory Usage: 13.6 MB, less than 94.25% of Python online submissions for Find All Anagrams in a String.
12+
"""
13+
class Solution(object):
14+
def findAnagrams(self, string, p):
15+
"""
16+
:type s: str
17+
:type p: str
18+
:rtype: List[int]
19+
"""
20+
result = []
21+
letters_needed = [0] * 26
22+
for letter in p:
23+
letters_needed[ord(letter) - ord('a')] += 1
24+
25+
curr_window = [0] * 26
26+
for i, letter in enumerate(string):
27+
#add to window
28+
curr_window[ord(letter) - ord('a')] += 1
29+
30+
#delete from window (once curr_window is long enough)
31+
if i >= len(p):
32+
letter_to_remove = string[i - len(p)]
33+
curr_window[ord(letter_to_remove) - ord('a')] -= 1
34+
35+
#compare window with target window
36+
if curr_window == letters_needed:
37+
anagram_start_idx = i + 1 - len(p) #same as i - (len(p) - 1)
38+
result.append(anagram_start_idx)
39+
40+
return result

567-permutation_in_string.py

+2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
"""
22
https://leetcode.com/problems/permutation-in-string/submissions/
33
4+
(Is pretty similar to 438. Find All Anagrams in a String)
5+
46
Strat:
57
Use sliding window. Initially, we preprocess s1 to see how many of each
68
letter we need (this becomes our "target" for the sliding window to match).

0 commit comments

Comments
 (0)