We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent c1d05fe commit 29cb955Copy full SHA for 29cb955
Find All Anagrams in a String/code.js
@@ -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