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
Changes from 1 commit
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
Next Next commit
Anagram func
m-aravind11 committed Apr 5, 2023
commit 9d7e1a13b0cb421596e384666673df1a58ff223e
23 changes: 23 additions & 0 deletions strings/strings.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package strings

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)
}
})
}
}