File tree 2 files changed +42
-0
lines changed
2 files changed +42
-0
lines changed Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change 1
1
"""
2
2
https://leetcode.com/problems/permutation-in-string/submissions/
3
3
4
+ (Is pretty similar to 438. Find All Anagrams in a String)
5
+
4
6
Strat:
5
7
Use sliding window. Initially, we preprocess s1 to see how many of each
6
8
letter we need (this becomes our "target" for the sliding window to match).
You can’t perform that action at this time.
0 commit comments