Prechádzať zdrojové kódy

add 'Valid Anagram' optimize

tangs 5 rokov pred
rodič
commit
07a776b315
1 zmenil súbory, kde vykonal 32 pridanie a 0 odobranie
  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)
+}