Skip to content

Instantly share code, notes, and snippets.

@theodesp
Last active September 17, 2019 14:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theodesp/e5d14abef030b8e108670a5ce8450036 to your computer and use it in GitHub Desktop.
Save theodesp/e5d14abef030b8e108670a5ce8450036 to your computer and use it in GitHub Desktop.
Check if 2 strings are anagrams #go
/*
To find if 2 strings are anagrams we simply put each letter of first into a frequency table. Then for each other letter of b we subtract that count.
At the end we have a frequency table that all the values are 0.
*/
func Anagrams(a string, b string) bool {
count := int32(0)
frequencies := make(map[rune]int32)
for _, val := range a {
frequencies[val] = frequencies[val] + 1
}
for _, val := range b {
frequencies[val] = frequencies[val] - 1
}
for _, val := range frequencies {
if val < 0 {
count += -(val)
} else {
count += val
}
}
return count == 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment