-
Notifications
You must be signed in to change notification settings - Fork 0
/
Lc0438Solution.java
58 lines (55 loc) · 1.64 KB
/
Lc0438Solution.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
49
50
51
52
53
54
55
56
57
58
package sliding_window;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Lc0438Solution {
public List<Integer> findAnagrams(String s, String p) {
if (s == null || s.length() < p.length()) {
return Collections.emptyList();
}
int[] windows = new int[26];
int[] need = new int[26];
for (int i = 0; i < p.length(); i++) {
need[p.charAt(i)-'a']++;
windows[s.charAt(i)-'a']++;
}
int count = 0;
for (int i = 0; i < 26; i++) {
if (windows[i] == need[i]) {
count++;
}
}
List<Integer> ret = new ArrayList<>();
if (count == 26) {
ret.add(0);
}
int pLen = p.length();
for (int i = 0; i < s.length() - pLen; i++) {
int l = s.charAt(i) - 'a', r = s.charAt(i + pLen) - 'a';
windows[r]++;
if (windows[r] == need[r]) {
count++;
} else if (windows[r] == need[r] + 1) {
count--;
}
// 顺序很重要
windows[l]--;
if (windows[l] == need[l]) {
count++;
} else if (windows[l] == need[l] - 1) {
count--;
}
if (count == 26) {
// emmm
ret.add(i+1);
}
}
return ret;
}
public static void main(String[] args) {
Lc0438Solution solution = new Lc0438Solution();
String s = "cbaebabacd";
String p = "abc";
System.out.println(solution.findAnagrams(s, p));
}
}