Skip to content

Commit f7955ef

Browse files
committed
Add solution #438
1 parent cb388b2 commit f7955ef

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -286,6 +286,7 @@
286286
434|[Number of Segments in a String](./0434-number-of-segments-in-a-string.js)|Easy|
287287
435|[Non-overlapping Intervals](./0435-non-overlapping-intervals.js)|Medium|
288288
437|[Path Sum III](./0437-path-sum-iii.js)|Medium|
289+
438|[Find All Anagrams in a String](./0438-find-all-anagrams-in-a-string.js)|Medium|
289290
441|[Arranging Coins](./0441-arranging-coins.js)|Easy|
290291
442|[Find All Duplicates in an Array](./0442-find-all-duplicates-in-an-array.js)|Medium|
291292
443|[String Compression](./0443-string-compression.js)|Medium|
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* 438. Find All Anagrams in a String
3+
* https://leetcode.com/problems/find-all-anagrams-in-a-string/
4+
* Difficulty: Medium
5+
*
6+
* Given two strings s and p, return an array of all the start indices of p's anagrams in s.
7+
*
8+
* You may return the answer in any order.
9+
*/
10+
11+
/**
12+
* @param {string} s
13+
* @param {string} p
14+
* @return {number[]}
15+
*/
16+
var findAnagrams = function(s, p) {
17+
const group = new Array(26).fill(0);
18+
const result = [];
19+
20+
for (let i = 0; i < p.length; i++) {
21+
group[p.charCodeAt(i) - 97]--;
22+
}
23+
24+
outer: for (let i = 0; i < s.length; i++) {
25+
group[s.charCodeAt(i) - 97]++;
26+
if (i < p.length - 1) {
27+
continue;
28+
} else if (i > p.length - 1) {
29+
group[s.charCodeAt(i - p.length) - 97]--;
30+
}
31+
for (let j = 0; j < 26; j++) {
32+
if (group[j]) {
33+
continue outer;
34+
}
35+
}
36+
result.push(i + 1 - p.length);
37+
}
38+
39+
return result;
40+
};

0 commit comments

Comments
 (0)