File tree Expand file tree Collapse file tree 1 file changed +59
-0
lines changed
Expand file tree Collapse file tree 1 file changed +59
-0
lines changed Original file line number Diff line number Diff line change 1+ # Time: O(n)
2+ # Space: O(1)
3+
4+ # Given a string s and a non-empty string p, find all the start indices
5+ # of p's anagrams in s.
6+ #
7+ # Strings consists of lowercase English letters only and the length of
8+ # both strings s and p will not be larger than 20,100.
9+ #
10+ # The order of output does not matter.
11+ #
12+ # Example 1:
13+ #
14+ # Input:
15+ # s: "cbaebabacd" p: "abc"
16+ #
17+ # Output:
18+ # [0, 6]
19+ #
20+ # Explanation:
21+ # The substring with start index = 0 is "cba", which is an anagram of "abc".
22+ # The substring with start index = 6 is "bac", which is an anagram of "abc".
23+ # Example 2:
24+ #
25+ # Input:
26+ # s: "abab" p: "ab"
27+ #
28+ # Output:
29+ # [0, 1, 2]
30+ #
31+ # Explanation:
32+ # The substring with start index = 0 is "ab", which is an anagram of "ab".
33+ # The substring with start index = 1 is "ba", which is an anagram of "ab".
34+ # The substring with start index = 2 is "ab", which is an anagram of "ab".
35+
36+ class Solution (object ):
37+ def findAnagrams (self , s , p ):
38+ """
39+ :type s: str
40+ :type p: str
41+ :rtype: List[int]
42+ """
43+ result = []
44+
45+ cnts = [0 ] * 26
46+ for c in p :
47+ cnts [ord (c ) - ord ('a' )] += 1
48+
49+ left , right = 0 , 0
50+ while right < len (s ):
51+ cnts [ord (s [right ]) - ord ('a' )] -= 1
52+ while left <= right and cnts [ord (s [right ]) - ord ('a' )] < 0 :
53+ cnts [ord (s [left ]) - ord ('a' )] += 1
54+ left += 1
55+ if right - left + 1 == len (p ):
56+ result .append (left )
57+ right += 1
58+
59+ return result
You can’t perform that action at this time.
0 commit comments