Skip to content

Commit 4684f49

Browse files
committed
Find all anagrams in a string
1 parent 36d290b commit 4684f49

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

0438_findAllAnagramsInAString.js

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* @param {string} s
3+
* @param {string} p
4+
* @return {number[]}
5+
*/
6+
7+
const isAnagram = (word, candidate) => {
8+
if (word.length !== candidate.length) return false;
9+
10+
const charMap = {};
11+
for (let index = 0; index < word.length; index++) {
12+
if (word.indexOf(candidate[index]) < 0) {
13+
return false;
14+
}
15+
charMap[word[index]] = charMap[word[index]] ? charMap[word[index]] + 1 : 1;
16+
charMap[candidate[index]] = charMap[candidate[index]] ? charMap[candidate[index]] - 1 : -1;
17+
}
18+
19+
return Object.keys(charMap).every(char => charMap[char] === 0);
20+
};
21+
22+
const findAnagrams = (s, p) => {
23+
const anagrams = {};
24+
anagrams[p] = true;
25+
26+
const answer = [];
27+
28+
const length = s.length - p.length + 1;
29+
for (let index = 0; index < length; index++) {
30+
const candidate = s.slice(index, index + p.length);
31+
32+
if (anagrams[candidate] === undefined) anagrams[candidate] = isAnagram(p, candidate);
33+
34+
if (anagrams[candidate]) answer.push(index);
35+
}
36+
37+
return answer;
38+
};

0 commit comments

Comments
 (0)