Browse Source

add 'Valid Anagram' optimize

tangs 5 years ago
parent
commit
07a776b315
1 changed files with 32 additions and 0 deletions
  1. 32 0
      tags/sort/validAnagram/main_optimize.go

+ 32 - 0
tags/sort/validAnagram/main_optimize.go

@@ -0,0 +1,32 @@
+package main
+
+import (
+	"fmt"
+	"sort"
+)
+
+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 {
+	sBys := []byte(s)
+	tBys := []byte(t)
+
+	sort.Slice(sBys, func(i, j int) bool {
+		return sBys[i] < sBys[j]
+	})
+	sort.Slice(tBys, func(i, j int) bool {
+		return tBys[i] < tBys[j]
+	})
+	return string(sBys) == string(tBys)
+}