forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0438-find-all-anagrams-in-a-string.js
42 lines (40 loc) · 1.18 KB
/
0438-find-all-anagrams-in-a-string.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
* @param {string} s
* @param {string} p
* @return {number[]}
*/
var findAnagrams = function (s, p) {
const charMap = new Map();
let matches = 0;
const matchIdx = [];
for (const char of p) {
const charCount = charMap.get(char) || 0;
charMap.set(char, charCount + 1);
}
let leftWindow = 0;
for (let rightWindow = 0; rightWindow < s.length; rightWindow++) {
const rightChar = s[rightWindow];
if (charMap.has(rightChar)) {
const rightCharCount = charMap.get(rightChar);
charMap.set(rightChar, rightCharCount - 1);
if (charMap.get(rightChar) === 0) {
matches++;
}
}
if (rightWindow >= p.length) {
const leftChar = s[leftWindow];
if (charMap.has(leftChar)) {
const leftCharCount = charMap.get(leftChar);
charMap.set(leftChar, leftCharCount + 1);
if (leftCharCount === 0) {
matches--;
}
}
leftWindow++;
}
if (matches === charMap.size) {
matchIdx.push(leftWindow);
}
}
return matchIdx;
};