思路:从左往右移动窗口,每次移动一格;移动的过程中不断对 left 与 right 指向的元素进行“是否存在于‘p’中“的判断——如果存在,那么对应字符的出现频率减一…..直到最后整个哈希表清零,就可以认为这个窗口中的元素满足条件,将其存入res中
1
2vector<int> findAnagrams(string s, string p)
3
4{
5
6 int ns = s.size(), np = p.size();
7
8 if(ns < np) return {};
9
10 std::vector<int> res;
11
12
13
14 std::vector<int> count(26, 0);
15
16 for(auto c : p) count[c - 'a']++;
17
18
19
20 int left = 0, right = 0, need = np;
21
22 while(right < ns)
23
24 {
25
26 char c = s[right];
27
28 // 扩大窗口
29
30 if(count[c - 'a'] > 0) need--;
31
32 count[c - 'a']--;
33
34 right++;
35
36
37
38 // 缩小窗口
39
40 if(right - left > np)
41
42 {
43
44 char d = s[left];
45
46 if(count[d - 'a'] >= 0) need++;
47
48 count[d - 'a']++;
49
50 left++;
51
52 }
53
54
55
56 if(need == 0) res.push_back(left);
57
58 }
59
60 return res;
61
62}