From 3f1552f981f62b1c9c09c2ace8a7263b18b0fac2 Mon Sep 17 00:00:00 2001 From: yoonsang lee Date: Wed, 18 Dec 2024 23:59:57 +0900 Subject: [PATCH] add: #242 valid anagram --- valid-anagram/ysle0.go | 46 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 valid-anagram/ysle0.go diff --git a/valid-anagram/ysle0.go b/valid-anagram/ysle0.go new file mode 100644 index 000000000..7725c2330 --- /dev/null +++ b/valid-anagram/ysle0.go @@ -0,0 +1,46 @@ +package main + +// package valid_anagram + +import ( + "fmt" +) + +func isAnagram(s string, t string) bool { + ht := make(map[rune]int, len(s)) + for _, r := range s { + ht[r]++ + } + + for _, r := range t { + cnt, ok := ht[r] + if !ok { + return false + } + + ht[r] -= 1 + if cnt-1 < 0 { + return false + } + } + + for _, v := range ht { + if v > 0 { + return false + } + } + + return true +} + +func main() { + r1 := isAnagram("anagram", "nagaram") + fmt.Println(r1) + fmt.Println() + + r2 := isAnagram("rat", "car") + fmt.Println(r2) + + r3 := isAnagram("ab", "a") + fmt.Println(r3) +}