LeetCode Problem: Find All Anagrams In A String
Problem statement:
You are given two strings, return an array of all indexes where p’s anagrams are starting in s
Example:
Input:
s = "cbaebabacd" p = "abc"
Expected output:
[0,6]
If you would like to solve the problem on Leetcode, here is the link to the problem: https://leetcode.com/problems/find-all-anagrams-in-a-string/
Golang Solution:
func findAnagrams(s string, p string) []int {
var result []int
if len(p) > len(s) {
return result
}
countS := make([]int, 26)
countP := make([]int, 26)
for i:=0; i<len(p); i++ {
countS[int(s[i]-'a')]++
countP[int(p[i]-'a')]++
}
start := 0
end := len(p)
if fmt.Sprint(countS) == fmt.Sprint(countP) {
result = append(result, start)
}
for end < len(s) {
countS[int(s[start]-'a')]--
countS[int(s[end]-'a')]++
if fmt.Sprint(countS) == fmt.Sprint(countP) {
result = append(result, start+1)
}
start++
end++
}
return result
}