438. Find All Anagrams in a String
Given a string s and a non-empty string p, find all the start indices of p's anagrams in s.
Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.
The order of output does not matter.
Example 1:
Input: s: "cbaebabacd" p: "abc" Output: [0, 6] Explanation: The substring with start index = 0 is "cba", which is an anagram of "abc". The substring with start index = 6 is "bac", which is an anagram of "abc".
Example 2:
Input: s: "abab" p: "ab" Output: [0, 1, 2] Explanation: The substring with start index = 0 is "ab", which is an anagram of "ab". The substring with start index = 1 is "ba", which is an anagram of "ab". The substring with start index = 2 is "ab", which is an anagram of "ab".
分析:
这题和mininum window几乎一摸一样,使用两个pointer来找这样的window。
1 class Solution: 2 def findAnagrams(self, s: str, p: str) -> List[int]: 3 from collections import defaultdict 4 letter_count = defaultdict(int) 5 start = end = 0 6 result = [] 7 for letter in p: 8 letter_count[letter] += 1 9 count = len(letter_count) 10 while end < len(s): 11 if s[end] in letter_count: 12 letter_count[s[end]] -= 1 13 if letter_count[s[end]] == 0: 14 count -= 1 15 end += 1 16 while count == 0 and start < len(s): 17 if end - start == len(p): 18 result.append(start) 19 if s[start] in letter_count: 20 letter_count[s[start]] += 1 21 if letter_count[s[start]] == 1: 22 count += 1 23 start += 1 24 return result

浙公网安备 33010602011771号