Last active
September 18, 2022 18:14
-
-
Save maxclav/8eb5a5ac16c91c097bb0ad139173d481 to your computer and use it in GitHub Desktop.
Check if two string variables are anagram in Go (GoLang).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package strings | |
// AreAnagram returns whether string `s` | |
// is an anagram of string `t` (true) or not (false). | |
func AreAnagram(s string, t string) bool { | |
if len(s) != len(t) { | |
return false | |
} | |
set1, set2 := buildMultiSets(s, t) | |
return set1.isEqualTo(set2) | |
} | |
type multiSet struct { | |
items map[byte]int | |
} | |
func newMultiSet() *multiSet { | |
return &multiSet{ | |
items: make(map[byte]int), | |
} | |
} | |
func buildMultiSets(str1, str2 string) (*multiSet, *multiSet) { | |
if len(s1) != len(s2) { | |
return nil, nil | |
} | |
set1, set2 := newMultiSet(), newMultiSet() | |
for i := 0; i < len(str1); i++ { | |
set1.add(str1[i]) | |
set2.add(str2[i]) | |
} | |
return set1, set2 | |
} | |
func (s *multiSet) add(b byte) { | |
if s.has(b) { | |
s.items[b]++ | |
} else { | |
s.items[b] = 1 | |
} | |
} | |
func (s *multiSet) has(b byte) bool { | |
_, ok := s.items[b] | |
return ok | |
} | |
func (s *multiSet) countOf(b byte) int { | |
c, ok := s.items[b] | |
if !ok { | |
return -1 | |
} | |
return c | |
} | |
func (s *multiSet) isEqualTo(s2 *multiSet) bool { | |
for b, c := range s.items { | |
if c != s2.countOf(b) { | |
return false | |
} | |
} | |
return true | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment