-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathPermutation in String.java
57 lines (48 loc) · 1.48 KB
/
Permutation in String.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
49
50
51
52
53
54
55
56
57
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];
for(int i = 0; i < s1.length(); i++) {
char c = s1.charAt(i);
char s = s2.charAt(i);
s1Count[c - 'a'] += 1;
s2Count[s - 'a'] += 1;
}
int matches = 0;
for(int i = 0; i < 26;i++) {
if(s1Count[i] == s2Count[i]) {
matches+=1;
}
}
int left = 0;
for(int right = s1.length(); right < s2.length();right++) {
if(matches == 26) {
return true;
}
int index = s2.charAt(right) - 'a';
s2Count[index] += 1;
if(s1Count[index] == s2Count[index]) {
matches += 1;
}
else if(s1Count[index] + 1 == s2Count[index]) {
matches -= 1;
}
index = s2.charAt(left) - 'a';
s2Count[index] -= 1;
if(s1Count[index] == s2Count[index]) {
matches += 1;
}
else if(s1Count[index] - 1 == s2Count[index]) {
matches -= 1;
}
left += 1;
}
if(matches == 26) {
return true;
}
return false;
}
}