diff --git a/strings/strings.go b/strings/strings.go new file mode 100644 index 0000000..8cd2324 --- /dev/null +++ b/strings/strings.go @@ -0,0 +1,29 @@ +package strings + +/** + Checks if two strings are perfect anagrams of each other using character count comparison. + Anagrams are formed by rearranging the letters of one string using all the original letters exactly once. + + Example: "listen" and "silent" are perfect anagrams of each other, while "now silent" and "listennow" are not. +**/ +func AreAnagrams(s1, s2 string) bool { + // If both strings are of unequal length, they are not anagrams + if len(s1) != len(s2) { + return false + } + + var charCount = make(map[rune]int) + + for _, ch := range s1 { + charCount[ch]++ + } + + for _, ch := range s2 { + charCount[ch]-- + if charCount[ch] < 0 { + return false + } + } + + return true +} diff --git a/strings/strings_test.go b/strings/strings_test.go new file mode 100644 index 0000000..8aad9d2 --- /dev/null +++ b/strings/strings_test.go @@ -0,0 +1,35 @@ +package strings + +import ( + "fmt" + "testing" +) + +func TestAreAnagrams(t *testing.T) { + tests := []struct { + s1 string + s2 string + want bool + }{ + {"", "", true}, + {"a", "a", true}, + {"aa", "aa", true}, + {"abcd", "dcba", true}, + {"anagram", "nag a ram", false}, + {"listen", "silent", true}, + {"abcdefg", "gfedcba", true}, + {"abc", "abcd", false}, + {"abcd", "dcbb", false}, + {":-;][=+", "+;=:", false}, + {":-asds;][=+", "+a;s[-d=:s]", true}, + {":-asds;][=+", "+;=:", false}, + {":-;][=+", "+asds;=:", false}, + } + for _, input := range tests { + t.Run(fmt.Sprintf("TestAreAnagrams(%v, %v)", input.s1, input.s2), func(t *testing.T) { + if got := AreAnagrams(input.s1, input.s2); got != input.want { + t.Errorf("AreAnagrams() = %v, want %v", got, input.want) + } + }) + } +}