Last active
September 17, 2019 14:31
-
-
Save theodesp/e5d14abef030b8e108670a5ce8450036 to your computer and use it in GitHub Desktop.
Check if 2 strings are anagrams #go
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
/* | |
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