|
@@ -0,0 +1,42 @@
|
|
|
+package main
|
|
|
+
|
|
|
+import "fmt"
|
|
|
+
|
|
|
+func main() {
|
|
|
+ var s, t string
|
|
|
+
|
|
|
+ s = "anagram"
|
|
|
+ t = "nagaram"
|
|
|
+ fmt.Println(isAnagram(s, t))
|
|
|
+
|
|
|
+ s = "rat"
|
|
|
+ t = "car"
|
|
|
+ fmt.Println(isAnagram(s, t))
|
|
|
+}
|
|
|
+
|
|
|
+// 通过记录字符个数来实现
|
|
|
+func isAnagram(s string, t string) bool {
|
|
|
+ var sRecord, tRecord = record(s), record(t)
|
|
|
+ if len(sRecord) != len(tRecord) {
|
|
|
+ return false
|
|
|
+ }
|
|
|
+ for k, sv := range sRecord {
|
|
|
+ if tv, ok := tRecord[k]; !ok {
|
|
|
+ return false
|
|
|
+ } else if sv != tv {
|
|
|
+ return false
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return true
|
|
|
+}
|
|
|
+
|
|
|
+func record(s string) map[byte]int {
|
|
|
+ var r = map[byte]int{}
|
|
|
+ for i := 0; i < len(s); i++ {
|
|
|
+ if _, ok := r[s[i]]; !ok {
|
|
|
+ r[s[i]] = 0
|
|
|
+ }
|
|
|
+ r[s[i]] = r[s[i]] + 1
|
|
|
+ }
|
|
|
+ return r
|
|
|
+}
|