滑动窗口
python
import collections
class Solution:
def findAnagrams(self, s: str, p: str):
left, right = 0, 0
m = len(s)
n = len(p)
valid = 0
needs = collections.Counter(p)
window = {}
res = []
while right < m:
c = s[right]
right += 1
if needs.get(c, -1) != -1:
if window.get(c, -1) == -1:
window[c] = 1
else:
window[c] += 1
if window[c] == needs[c]:
valid += 1
while right - left == n:
if valid == len(needs):
res.append(left)
d = s[left]
left += 1
if needs.get(d, -1) != -1:
if window[d] == needs[d]:
valid -= 1
window[d] -=1
return res
c++
class Solution {
public:
vector<int> findAnagrams(string s, string p) {
// 滑动窗口
unordered_map<char, int> need;
unordered_map<char, int> window;
int left = 0, right = 0;
int valid = 0;
vector<int> res;
// 将p的字符哈希表化
for (auto& c : p) {
need[c]++;
}
int target = need.size();
while (right < s.size()) {
// 扩大窗口
char c = s[right];
right++;
window[c]++;
if (window[c] == need[c]) {
valid++;
}
// 窗口长度超过p的长度,缩小窗口
while (right - left >= p.size()) {
if (valid == target) {
res.emplace_back(left);
}
char d = s[left];
left++;
if(window[d] == need[d]) valid--;
window[d]--;
}
}
return res;
}
};