【Leetcode】438. 找到字符串中所有字母异位词
题目链接
【Leetcode】438. 找到字符串中所有字母异位词
代码
func findAnagrams(s string, p string) []int {
cnt := map[byte]int{}
for idx := range p {
cnt[p[idx]]++
}
total := len(cnt)
lenS, lenP := len(s), len(p)
i, j := 0, 0
ans := []int{}
time := 0
for j < lenS {
cnt[s[j]]--
if cnt[s[j]] == -1 {
time--
} else if cnt[s[j]] == 0 {
time++
}
if j-i+1 > lenP {
cnt[s[i]]++
if cnt[s[i]] == 0 {
time++
} else if cnt[s[i]] == 1 {
time--
}
i++
}
j++
if time == total {
ans = append(ans, i)
}
}
return ans
}