1
class Solution {
2
public boolean checkInclusion(String s1, String s2) {
3
if (s1.length() > s2.length()) {
4
return false;
5
}
6

7
int[] s1Count = new int[26];
8
int[] s2Count = new int[26];
9

10
for (int i = 0; i < s1.length(); i++) {
11
char c = s1.charAt(i);
12
char s = s2.charAt(i);
13
s1Count[c - 'a'] += 1;
14
s2Count[s - 'a'] += 1;
15
}
16

17
int matches = 0;
18

19
for (int i = 0; i < 26; i++) {
20
if (s1Count[i] == s2Count[i]) {
21
matches += 1;
22
}
23
}
24

25
int left = 0;
26
for (int right = s1.length(); right < s2.length(); right++) {
27
if (matches == 26) {
28
return true;
29
}
30

31
int index = s2.charAt(right) - 'a';
32
s2Count[index] += 1;
33
if (s1Count[index] == s2Count[index]) {
34
matches += 1;
35
} else if (s1Count[index] + 1 == s2Count[index]) {
36
matches -= 1;
37
}
38

39
index = s2.charAt(left) - 'a';
40
s2Count[index] -= 1;
41
if (s1Count[index] == s2Count[index]) {
42
matches += 1;
43
} else if (s1Count[index] - 1 == s2Count[index]) {
44
matches -= 1;
45
}
46
left += 1;
47
}
48

49
if (matches == 26) {
50
return true;
51
}
52

53
return false;
54
}
55
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0