6
[Golang] Check Whether Two Strings Are Anagram of Each Other
source link: https://siongui.github.io/2017/05/06/go-check-if-two-string-are-anagram/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
[Golang] Check Whether Two Strings Are Anagram of Each Other
May 06, 2017Check whether two strings are anagram of each other in Go programming language.
Check by sorting [1]:
- sort both strings [3]
- compare the sorted strings
Another way to check anagram is by characters count, see [4].
package anagram import ( "sort" ) type ByRune []rune func (r ByRune) Len() int { return len(r) } func (r ByRune) Swap(i, j int) { r[i], r[j] = r[j], r[i] } func (r ByRune) Less(i, j int) bool { return r[i] < r[j] } func StringToRuneSlice(s string) []rune { var r []rune for _, runeValue := range s { r = append(r, runeValue) } return r } func AreAnagram(s1, s2 string) bool { var r1 ByRune = StringToRuneSlice(s1) var r2 ByRune = StringToRuneSlice(s2) sort.Sort(r1) sort.Sort(r2) return string(r1) == string(r2) }
Testing:
package anagram import ( "testing" ) func TestAreAnagram(t *testing.T) { if AreAnagram("listen", "silent") != true { t.Error(`"listen", "silent"`) } if AreAnagram("test", "ttew") != false { t.Error(`"test", "ttew"`) } if AreAnagram("geeksforgeeks", "forgeeksgeeks") != true { t.Error(`"geeksforgeeks", "forgeeksgeeks"`) } if AreAnagram("triangle", "integral") != true { t.Error(`"triangle", "integral"`) } if AreAnagram("abd", "acb") != false { t.Error(`"abd", "acb"`) } }
Tested on:
- Ubuntu Linux 17.04, Go 1.8.1
- Go Playground
References:
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK