-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfindanagramsinstring.java
More file actions
40 lines (36 loc) · 986 Bytes
/
findanagramsinstring.java
File metadata and controls
40 lines (36 loc) · 986 Bytes
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
package Interview;
import java.util.ArrayList;
import java.util.List;
public class findanagramsinstring {
public static void main(String[] args){
findAnagrams("cbaebabacd","abc");
}
public static List<Integer> findAnagrams(String s, String p) {
List<Integer> result = new ArrayList<>();
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()){
if(hash[s.charAt(right)]>=1){
count--;
}
hash[s.charAt(right)]--;
right++;
if(count==0){
result.add(left);
}
if(right-left==p.length()){
if(hash[s.charAt(left)]>=0){
count++;
}
hash[s.charAt(left)]++;
left++;
}
}
return result;
}
}