-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy pathFindAllAnagramsinaString.java
More file actions
49 lines (35 loc) · 896 Bytes
/
FindAllAnagramsinaString.java
File metadata and controls
49 lines (35 loc) · 896 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
41
42
43
44
45
46
47
48
49
/*
Source: https://leetcode.com/problems/find-all-anagrams-in-a-string/
Time: O(n), where n is the length of the given string(s)
Space: O(n), list is needed to store the starting indices of anagrams
*/
class Solution {
public List<Integer> findAnagrams(String s, String p) {
int sLen = s.length();
int pLen = p.length();
if(sLen < pLen) {
return new ArrayList<>();
}
char[] hash = new char[26];
for(int i = 0; i < pLen; i++) {
++hash[p.charAt(i) - 'a'];
}
int left = 0;
int right = 0;
List<Integer> pos = new ArrayList<>();
while(right < sLen) {
int index = s.charAt(right) - 'a';
if(hash[index] > 0) {
--hash[index];
++right;
} else {
++hash[s.charAt(left) - 'a'];
++left;
}
if(right - left == pLen) {
pos.add(left);
}
}
return pos;
}
}