forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.ts
43 lines (37 loc) · 954 Bytes
/
Solution.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
function checkInclusion(s1: string, s2: string): boolean {
// 滑动窗口方案
if (s1.length > s2.length) {
return false;
}
const n = s1.length;
const m = s2.length;
const toCode = (s: string) => s.charCodeAt(0) - 97;
const isMatch = () => {
for (let i = 0; i < 26; i++) {
if (arr1[i] !== arr2[i]) {
return false;
}
}
return true;
};
const arr1 = new Array(26).fill(0);
for (const s of s1) {
const index = toCode(s);
arr1[index]++;
}
const arr2 = new Array(26).fill(0);
for (let i = 0; i < n; i++) {
const index = toCode(s2[i]);
arr2[index]++;
}
for (let l = 0, r = n; r < m; l++, r++) {
if (isMatch()) {
return true;
}
const i = toCode(s2[l]);
const j = toCode(s2[r]);
arr2[i]--;
arr2[j]++;
}
return isMatch();
}