Skip to content

Commit 40f861f

Browse files
Sean PrashadSean Prashad
authored andcommitted
Update 567_Permutation_in_String.java
1 parent 3b0e996 commit 40f861f

File tree

1 file changed

+24
-24
lines changed

1 file changed

+24
-24
lines changed
Lines changed: 24 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,44 +1,44 @@
11
class Solution {
22
public boolean checkInclusion(String s1, String s2) {
3-
if (s1 == null || s2.length() < s1.length()) {
3+
if (s1 == null || s1.length() == 0 || s1.length() > s2.length()) {
44
return false;
55
}
66

7-
int[] lookup = new int[26];
7+
Map<Character, Integer> hm = new HashMap<>();
88

9-
for (int i = 0; i < s1.length(); i++) {
10-
lookup[s1.charAt(i) - 'a']++;
9+
for (char c : s1.toCharArray()) {
10+
hm.put(c, hm.getOrDefault(c, 0) + 1);
1111
}
1212

13-
int start = 0, end = s1.length() - 1;
13+
int s = 0, e = 0, counter = hm.size();
1414

15-
while (end < s2.length()) {
16-
for (int i = start; i <= end; i++) {
17-
lookup[s2.charAt(i) - 'a']--;
18-
}
15+
while (e < s2.length()) {
16+
if (hm.containsKey(s2.charAt(e))) {
17+
hm.put(s2.charAt(e), hm.get(s2.charAt(e)) - 1);
1918

20-
if (allZeros(lookup)) {
21-
return true;
19+
if (hm.get(s2.charAt(e)) == 0) {
20+
--counter;
21+
}
2222
}
2323

24-
for (int i = start; i <= end; i++) {
25-
lookup[s2.charAt(i) - 'a']++;
26-
}
24+
++e;
2725

28-
start++;
29-
end++;
30-
}
26+
if (e - s > s1.length()) {
27+
if (hm.containsKey(s2.charAt(s))) {
28+
if (hm.get(s2.charAt(s)) == 0) {
29+
++counter;
30+
}
31+
hm.put(s2.charAt(s), hm.get(s2.charAt(s)) + 1);
32+
}
3133

32-
return false;
33-
}
34+
++s;
35+
}
3436

35-
private boolean allZeros(int[] lookup) {
36-
for (int i = 0; i < lookup.length; i++) {
37-
if (lookup[i] != 0) {
38-
return false;
37+
if (counter == 0 && e - s == s1.length()) {
38+
return true;
3939
}
4040
}
4141

42-
return true;
42+
return false;
4343
}
4444
}

0 commit comments

Comments
 (0)