lc-day16

每日一题 & js练习

438. 找到字符串中所有字母异位词

题目

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
var findAnagrams = function(s, p) {
const sLen = s.length, pLen = p.length;
if(sLen < pLen) return [];

const ans = [];
const sCount = new Array(26).fill(0);
const pCount = new Array(26).fill(0);
for(let i = 0; i < pLen; i++){
++sCount[s[i].charCodeAt() - 'a'.charCodeAt()];
++pCount[p[i].charCodeAt() - 'a'.charCodeAt()];
}
if(sCount.toString() === pCount.toString()){
ans.push(0);
}
for(let i = 0; i < sLen - pLen; i++){
--sCount[s[i].charCodeAt() - 'a'.charCodeAt()];
++sCount[s[i + pLen].charCodeAt() - 'a'.charCodeAt()];
if(sCount.toString() == pCount.toString()) ans.push(i + 1);
}
return ans;

};