Skip to content

Commit 29cb955

Browse files
committed
added Function
1 parent c1d05fe commit 29cb955

File tree

1 file changed

+33
-0
lines changed
  • Find All Anagrams in a String

1 file changed

+33
-0
lines changed

Find All Anagrams in a String/code.js

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/*
2+
* @param {string} s
3+
* @param {string} p
4+
* @return {number[]}
5+
*/
6+
var findAnagrams = function(s, p) {
7+
const results = [];
8+
const map = new Map();
9+
for (const letter of p) {
10+
map.set(letter, (map.get(letter) || 0) + 1);
11+
}
12+
13+
let needed = map.size;
14+
for (let i = 0, j = 0; j < s.length; j++) {
15+
const left = s[i], right = s[j];
16+
17+
if (map.has(right)) {
18+
map.set(right, map.get(right) - 1);
19+
if (!map.get(right)) needed--;
20+
}
21+
22+
if (j - i + 1 === p.length) {
23+
if (!needed) results.push(i);
24+
if (map.has(left)) {
25+
const previous = map.get(left);
26+
map.set(left, map.get(left) + 1);
27+
if (map.get(left) > 0 && previous <= 0) needed++;
28+
}
29+
i++;
30+
}
31+
}
32+
return results;
33+
};

0 commit comments

Comments
 (0)