The next problem in our Leetcode journey is the Is Anagram problem whose rules are as follows: "Given two strings s and t, return true if the two strings are anagrams of each other, otherwise return false."
The solution will be to create and compare a hashmap of each strings letters where the keys are the letters and the values are the count of each letter.
import (
// Allows us to compare Maps
"maps"
)
func IsAnagram(s, t string) bool {
sMap := make(map[rune]int)
tMap := make(map[rune]int)
for _, char := range s {
_, prs := sMap[char]
if prs == true {
sMap[char]++
} else {
sMap[char] = 1
}
}
for _, char := range t {
_, prs := sMap[char]
if prs == true {
tMap[char]++
} else {
tMap[char] = 1
}
}
return maps.Equal(sMap, tMap)
}
Of course this can alternativly be complete with use of a helper function MakeMap() to preserve the DRY principal.
func MakeMap(s string) map[rune]int {
strMap := make(map[rune]int)
for _, char := range s {
_, prs := strMap[char]
if prs == true {
strMap[char]++
} else {
strMap[char] = 1
}
}
return strMap
}
func IsAnagram(s, t string) bool {
sMap := MakeMap(s)
tMap := MakeMap(t)
return maps.Equal(sMap, tMap)
}