Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature | Function to check if two words are anagrams of each other #8

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions strings/strings.go
Original file line number Diff line number Diff line change
@@ -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
}
35 changes: 35 additions & 0 deletions strings/strings_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
})
}
}