package top100liked import ( "fmt" "testing" ) // https://leetcode.cn/problems/find-all-anagrams-in-a-string/description/?envType=study-plan-v2&envId=top-100-liked func findAnagrams(s string, p string) []int { result := []int{} if len(s) < len(p) { return result } // p 的字符计数 pCount := [26]int{} for i := 0; i < len(p); i++ { pCount[p[i]-'a']++ } // 窗口计数 wCount := [26]int{} // 先初始化第一个窗口 [0, len(p)-1] for i := 0; i < len(p); i++ { wCount[s[i]-'a']++ } // 比较第一个窗口 if wCount == pCount { result = append(result, 0) } // 滑动窗口 for i := len(p); i < len(s); i++ { // 加入新字符 wCount[s[i]-'a']++ // 移除左边界字符 wCount[s[i-len(p)]-'a']-- // 比较 if wCount == pCount { result = append(result, i-len(p)+1) } } return result } func TestS9(t *testing.T) { fmt.Printf("%+v", findAnagrams("cbaebabacd", "abc")) }