Skip to content

Commit 7e5e215

Browse files
authored
Merge pull request #1861 from tahsintunan/438
Update 438. Find All Anagrams in a String with more performant code
2 parents a4c62df + f6130b7 commit 7e5e215

File tree

1 file changed

+28
-35
lines changed

1 file changed

+28
-35
lines changed

Diff for: go/0438-find-all-anagrams-in-a-string.go

+28-35
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,31 @@
11
func findAnagrams(s string, p string) []int {
2-
startIndex := 0
3-
pMap := make(map[byte]int)
4-
sMap := make(map[byte]int)
5-
var res []int
6-
7-
for i := 0; i < len(p); i++ {
8-
pMap[p[i]] = 1 + pMap[p[i]]
9-
}
10-
11-
for i := 0; i < len(s); i++ {
12-
sMap[s[i]] = 1 + sMap[s[i]]
13-
14-
if i >= len(p) - 1 {
15-
if equals(sMap, pMap) {
16-
res = append(res, startIndex)
17-
}
18-
19-
if _, ok := sMap[s[startIndex]]; ok {
20-
sMap[s[startIndex]] = sMap[s[startIndex]] - 1
21-
if sMap[s[startIndex]] == 0 {
22-
delete(sMap, s[startIndex])
23-
}
24-
}
25-
startIndex += 1
26-
}
27-
}
28-
return res
29-
}
2+
len_s, len_p := len(s), len(p)
3+
if len_p > len_s {
4+
return []int{}
5+
}
6+
7+
ans := make([]int, 0, len_s)
8+
count_p, count_s := count(p), count(s[:len_p])
9+
10+
if count_p == count_s {
11+
ans = append(ans, 0)
12+
}
3013

31-
func equals(a, b map[byte]int) bool {
32-
for k, v := range a {
33-
if b[k] != v {
34-
return false
35-
}
36-
}
37-
return true
14+
for i := len_p; i < len_s; i++ {
15+
count_s[int(s[i-len_p]-'a')]--
16+
count_s[int(s[i]-'a')]++
17+
if count_p == count_s {
18+
ans = append(ans, i-len_p+1)
19+
}
20+
}
21+
22+
return ans
3823
}
24+
25+
func count(s string) [26]int {
26+
arr := [26]int{}
27+
for _, r := range []rune(s) {
28+
arr[int(r-'a')]++
29+
}
30+
return arr
31+
}

0 commit comments

Comments
 (0)