Tuesday, December 20, 2022
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
func isAnagram(s string, t string) bool {
if len(s)!=len(t) {
return false
}
sourceArray := []byte(s)
// descending sort
sort.Slice(sourceArray, func(i, j int) bool {
return sourceArray[i] < sourceArray[j]
})
// descending sort
targetArray := []byte(t)
sort.Slice(targetArray, func(i, j int) bool {
return targetArray[i] < targetArray[j]
})
return bytes.Equal(sourceArray,targetArray)
}
import "strings"
func isAnagram(s string, t string) bool {
if len(s) != len(t) {
return false
}
for _, rune := range s {
frequencyS := strings.Count(s, string(rune))
frequencyT := strings.Count(t, string(rune))
if (frequencyS != frequencyT) {
return false
}
}
return true
}
func isAnagram(s string, t string) bool {
if len(s) != len(t) {
return false
}
sourceMap := make(map[rune]int)
targetMap := make(map[rune]int)
for _, char := range s {
sourceMap[char]++
}
for _, char := range t {
targetMap[char]++
}
for char, sourceCount := range sourceMap {
if targetCount, exists := targetMap[letter]; !exists || sourceCount != targetCount {
return false
}
}
return true
}