解题思路

思路同经典的76.最小覆盖子串,https://leetcode-cn.com/problems/minimum-window-substring/solution/c-hua-dong-chuang-kou-z-by-zrita/

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
vector<int> findAnagrams(string s, string p) {
vector<int> res;
int m[128] = {0};
int left = 0, right = 0, need = 0;
for(char c : p)
++m[c];
while(right < s.size())
{
if(m[s[right]] > 0) ++need;
--m[s[right]];
++right;
while(need == p.size())
{
if(right - left == p.size()) res.push_back(left); //通过长度判断异位词,加入res中
if(m[s[left]] == 0) --need;
++m[s[left]];
++left;
}
}
return res;
}
};