forked from xiaoyaoworm/Leetcode-java
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path438_findAnagrams.java
37 lines (31 loc) · 992 Bytes
/
438_findAnagrams.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
public class Solution {
public List<Integer> findAnagrams(String s, String p) {
List<Integer> res = new ArrayList<Integer>();
if(s == null || p == null || s.length() == 0 || p.length() == 0 || s.length() < p.length()) return res;
int[] hash = new int[256];
for(char c: p.toCharArray()){
hash[c]++;
}
int left = 0;
int right = 0;
int count = p.length();
while(right < s.length()){
char r = s.charAt(right);
if(hash[r] >= 1){
count--;
}
hash[r]--;
right++;
if(count == 0) res.add(left);
if(right-left == p.length()){
char l = s.charAt(left);
if(hash[l]>= 0){
count++;
}
hash[l]++;
left++;
}
}
return res;
}
}