Skip to content

Commit

Permalink
Create 0438-find-all-anagrams-in-a-string.js
Browse files Browse the repository at this point in the history
  • Loading branch information
andynullwong committed Dec 30, 2022
1 parent 2d0e0cc commit b4a3c08
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions javascript/0438-find-all-anagrams-in-a-string.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,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;
};

0 comments on commit b4a3c08

Please sign in to comment.