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
| func findAnagrams(s string, p string) []int {
var res []int
if len(s) == 0 || len(p) == 0 {
return res
}
need := make(map[byte]int)
for i := 0; i < len(p); i++ {
need[p[i]]++
}
left, right := 0, 0
size := len(need)
for right < len(s) {
if count, exists := need[s[right]]; exists {
need[s[right]]--
if count == 1 {
size--
}
}
// 当窗口大小等于p的长度时,检查是否是异位词
if right-left+1 == len(p) {
if size == 0 {
res = append(res, left)
}
// 缩小窗口
if count, exists := need[s[left]]; exists {
need[s[left]]++
if count == 0 {
size++
}
}
left++
}
right++
}
return res
}
|