MCPcopy Create free account
hub / github.com/austingebauer/go-leetcode / isAnagram0

Function isAnagram0

valid_anagram_242/solution.go:32–71  ·  view source on GitHub ↗
(s string, t string)

Source from the content-addressed store, hash-verified

30}
31
32func isAnagram0(s string, t string) bool {
33 if len(s) != len(t) {
34 return false
35 }
36
37 // build a character to frequency map
38 freq := make(map[uint8]int)
39 for i := 0; i < len(s); i++ {
40 _, ok := freq[s[i]]
41 if !ok {
42 freq[s[i]] = 1
43 } else {
44 freq[s[i]] += 1
45 }
46 }
47
48 // look over anagram in question and decrement frequencies
49 for i := 0; i < len(s); i++ {
50 f, ok := freq[t[i]]
51 if !ok {
52 return false
53 }
54
55 // if frequency drops below 0, return false early
56 if f-1 < 0 {
57 return false
58 }
59
60 freq[t[i]] -= 1
61 }
62
63 // verify that all frequencies are 0 for a valid anagram
64 for _, v := range freq {
65 if v != 0 {
66 return false
67 }
68 }
69
70 return true
71}

Callers 1

Test_isAnagramFunction · 0.85

Calls

no outgoing calls

Tested by 1

Test_isAnagramFunction · 0.68