-
Notifications
You must be signed in to change notification settings - Fork 12
/
solution.java
35 lines (30 loc) · 1.02 KB
/
solution.java
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
class Solution {
public boolean checkInclusion(String s1, String s2) {
if (s1.length() > s2.length())
return false;
int[] s1Count = new int[26];
int[] s2Count = new int[26];
// Count the frequency of characters in s1 and the first window of s2
for (int i = 0; i < s1.length(); i++) {
s1Count[s1.charAt(i) - 'a']++;
s2Count[s2.charAt(i) - 'a']++;
}
// Slide the window over s2
for (int i = 0; i < s2.length() - s1.length(); i++) {
if (matches(s1Count, s2Count))
return true;
// Update the window
s2Count[s2.charAt(i) - 'a']--;
s2Count[s2.charAt(i + s1.length()) - 'a']++;
}
// Check the last window
return matches(s1Count, s2Count);
}
private boolean matches(int[] s1Count, int[] s2Count) {
for (int i = 0; i < 26; i++) {
if (s1Count[i] != s2Count[i])
return false;
}
return true;
}
}