滑动窗口来解决这一题
将两者都放入数组计数器中进行比较。
s的窗口大小维持在p.length的大小,随时进行缩减(第13行判断)
滑动窗口
var findAnagrams = function (s, p) {
let sCount = new Array(26).fill(0)
let pCount = new Array(26).fill(0)
let a = 'a'.charCodeAt(0)
let sLength = s.length
let pLength = p.length
let res = []
for (let c of p) {
pCount[c.charCodeAt(0) - a]++
}
for (let i = 0; i < sLength; ++i) {
sCount[s[i].charCodeAt(0) - a]++
if (i >= pLength) {
// 去掉 s 最左边的元素
sCount[s[i - pLength].charCodeAt(0) - a]--
}
if (pCount.toString() === sCount.toString()) {
res.push(i - pLength + 1)
}
}
return res
};