Skip to content

Commit cbb9853

Browse files
authored
Update 438-find-all-anagrams-in-a-string.js
1 parent de5fb1f commit cbb9853

File tree

1 file changed

+19
-27
lines changed

1 file changed

+19
-27
lines changed

438-find-all-anagrams-in-a-string.js

Lines changed: 19 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -3,34 +3,26 @@
33
* @param {string} p
44
* @return {number[]}
55
*/
6-
const findAnagrams = function(s, p) {
7-
const slen = s.length
8-
const plen = p.length
9-
if( plen > slen ) {
10-
return []
6+
const findAnagrams = function (s, p) {
7+
const slen = s.length;
8+
const plen = p.length;
9+
if (plen > slen) return [];
10+
const aCode = "a".charCodeAt(0);
11+
const count = new Array(26).fill(0);
12+
for (let i = 0; i < plen; i++) count[p.charCodeAt(i) - aCode] += 1;
13+
const res = [];
14+
for (let i = 0; i < slen; i++) {
15+
count[s.charCodeAt(i) - aCode] -= 1;
16+
if (i >= plen - 1) {
17+
if (i - plen >= 0) count[s.charCodeAt(i - plen) - aCode] += 1;
18+
if (allZero(count)) res.push(i - plen + 1);
1119
}
12-
const aCode = ('a').charCodeAt(0)
13-
const count = new Array(26).fill(0)
14-
for(let i = 0; i < plen; i++) {
15-
count[ p.charCodeAt(i) - aCode ] += 1
16-
}
17-
const res = []
18-
for(let i = 0; i < slen; i++) {
19-
count[ s.charCodeAt(i) - aCode ] -= 1
20-
if (i >= plen - 1) {
21-
if(i - plen >= 0) count[ s.charCodeAt( i - plen ) - aCode ] += 1
22-
if (allZero(count)) {
23-
res.push(i - plen + 1)
24-
}
25-
}
26-
}
27-
28-
return res
20+
}
21+
return res;
2922
};
30-
3123
function allZero(count) {
32-
for(let el of count) {
33-
if(el !== 0) return false
34-
}
35-
return true
24+
for (let el of count) {
25+
if (el !== 0) return false;
26+
}
27+
return true;
3628
}

0 commit comments

Comments
 (0)