438. Find All Anagrams in a String

思路:定长滑窗,写代码的时候,记得枚举右端点,写出左端点。
js
/**
* @param {string} s
* @param {string} p
* @return {number[]}
*/
var findAnagrams = function (s, p) {
const cntS = new Array(26).fill(0)
const cntP = new Array(26).fill(0)
const ans = []
const n = s.length
for (const c of p) {
cntP[c.charCodeAt() - 'a'.charCodeAt()]++
}
for (let right = 0; right < n; right++) {
// 明确写出左端点,不容易出错
const left = right - p.length + 1
cntS[s[right].charCodeAt() - 'a'.charCodeAt()]++
if (left < 0) {
continue
}
if (_.isEqual(cntS, cntP)) {
ans.push(left)
}
cntS[s[left].charCodeAt() - 'a'.charCodeAt()]--
}
return ans
}