-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPermutationString.java
48 lines (41 loc) · 1.25 KB
/
PermutationString.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
36
37
38
39
40
41
42
43
44
45
46
47
48
public class PermutationString {
public boolean checkInclusion(String s1, String s2) {
if (s1.length() > s2.length()) {
return false;
}
int[] s1Count = new int[26];
int[] s2Count = new int[26];
for (int i = 0; i < s1.length(); i++) {
s1Count[s1.charAt(i) - 'a']++;
s2Count[s2.charAt(i) - 'a']++;
}
int matches = 0;
for (int i = 0; i < 26; i++) {
if (s1Count[i] == s2Count[i]) {
matches++;
}
}
int l = 0;
for (int r = s1.length(); r < s2.length(); r++) {
if (matches == 26) {
return true;
}
int index = s2.charAt(r) - 'a';
s2Count[index]++;
if (s1Count[index] == s2Count[index]) {
matches++;
} else if (s1Count[index] + 1 == s2Count[index]) {
matches--;
}
index = s2.charAt(l) - 'a';
s2Count[index]--;
if (s1Count[index] == s2Count[index]) {
matches++;
} else if (s1Count[index] - 1 == s2Count[index]) {
matches--;
}
l++;
}
return matches == 26;
}
}