function findAnagrams(s, t) {
// 创建两个对象,分别用于存储目标字符串的字符计数和滑动窗口的字符计数
const need = {};
const window = {};
for (let char of t) {
need[char] = (need[char] || 0) + 1;
}
let left = 0;
let right = 0;
let valid = 0;
const res = [];
while (right < s.length) {
const c = s[right];
right++;
// 进行窗口内数据的一系列更新
if (need[c]) {
window[c] = (window[c] || 0) + 1;
if (window[c] === need[c]) {
valid++;
}
}
// 判断左侧窗口是否要收缩
while (right - left >= t.length) {
// 当窗口符合条件时,把起始索引加入 res
if (valid === Object.keys(need).length) {
res.push(left);
}
const d = s[left];
left++;
// 进行窗口内数据的一系列更新
if (need[d]) {
if (window[d] === need[d]) {
valid--;
}
window[d]--;
}
}
}
return res;
}
console.log(findAnagrams("cbaebabacd", 'abc'));
438找到字符串中所有字母的异位词
最新推荐文章于 2024-09-05 11:00:53 发布