-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFindAllAnagramsinString.java
48 lines (31 loc) · 1.21 KB
/
FindAllAnagramsinString.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
38
39
40
41
42
43
44
45
46
47
48
public class FindAllAnagramsinString {
/**
* Question : https://leetcode.com/explore/challenge/card/may-leetcoding-challenge/536/week-3-may-15th-may-21st/3332/
*/
class Solution {
public List<Integer> findAnagrams(String s, String p) {
List<Integer> result = new ArrayList<Integer>();
if (s == null || s.length() == 0 || p == null || p.length() == 0) return result;
int[] char_count = new int[26];
for (int i = 0; i < p.length(); i++)
char_count[p.charAt(i) - 'a']++;
int left = 0, right = 0, count = p.length();
while (right < s.length()) {
if (char_count[s.charAt(right) - 'a'] >= 1) count--;
char_count[s.charAt(right) - 'a']--;
right++;
if (count == 0) {
result.add(left);
}
if (right - left == p.length()) {
if (char_count[s.charAt(left) - 'a'] >= 0) {
count++;
}
char_count[s.charAt(left) - 'a']++;
left++;
}
}
return result;
}
}
}