5

[Golang] Anagram Check by Characters Count

 2 years ago
source link: http://siongui.github.io/2017/05/08/go-anagram-check-by-char-count/
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.
neoserver,ios ssh client

[Golang] Anagram Check by Characters Count

May 08, 2017

Check whether two strings are anagram of each other in Go programming language.

Check by characters count:

  1. setup map structures to count the characters of both strings [2].
  2. compare if the two map structures are equal [3] via reflect.DeepEqual.

Another way to check anagram is by sorting, see [1].

Run Code on Go Playground

package anagram

import (
      "reflect"
)

func GetCharCount(s string) (c map[rune]int) {
      c = make(map[rune]int)
      for _, runeValue := range s {
              if _, ok := c[runeValue]; ok {
                      c[runeValue] += 1
              } else {
                      c[runeValue] = 1
              }
      }
      return
}

func AreAnagram(s1, s2 string) bool {
      c1 := GetCharCount(s1)
      c2 := GetCharCount(s2)

      return reflect.DeepEqual(c1, c2)
}

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:


References:


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK