-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindAnagram.java
More file actions
34 lines (32 loc) · 977 Bytes
/
FindAnagram.java
File metadata and controls
34 lines (32 loc) · 977 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
// 438. Find All Anagrams in a String
import java.util.ArrayList;
import java.util.List;
class Solution {
public List<Integer> findAnagrams(String s, String p) {
ArrayList<Integer> list = new ArrayList<>();
if(s.length() < p.length()) return list;
int[] count = new int[26];
for(char c : p.toCharArray()){
count[c - 'a']++;
}
int left = 0, right =0, needed = p.length();
while(right < s.length()){
if(count[s.charAt(right) -'a'] > 0){
needed--;
}
count[s.charAt(right) - 'a']--;
right++;
if (needed == 0) {
list.add(left);
}
if (right - left == p.length()) {
if (count[s.charAt(left) - 'a'] >= 0) {
needed++;
}
count[s.charAt(left) - 'a']++;
left++;
}
}
return list;
}
}