标签:
1 package main 2 3 import ( 4 "crypto/md5" 5 "encoding/hex" 6 "fmt" 7 "time" 8 ) 9 10 func GetMd5(value string) string { 11 m := md5.New() 12 m.Write([]byte(value)) 13 c := m.Sum(nil) 14 return hex.EncodeToString(c) 15 } 16 17 func main() { 18 var arr [1000000]string 19 var tree TrieTree 20 tree.Init() 21 for i := 0; i < 1000000; i++ { 22 arr[i] = GetMd5(string(i)) 23 } 24 25 s := time.Nanosecond 26 fmt.Println(s) 27 28 for i := 0; i < 999900; i++ { 29 tree.AddWord(arr[i]) 30 } 31 e := time.Nanosecond 32 fmt.Println((e - s) / 1000000) 33 34 s = time.Nanosecond 35 for i := 0; i < 999900; i++ { 36 tree.FindWord(arr[i]) 37 // find := tree.FindWord(arr[i]) 38 //fmt.Println(find) 39 } 40 e = time.Nanosecond 41 fmt.Println(e) 42 43 fmt.Println((e - s) / 1000000) 44 45 fmt.Println("Done!") 46 } 47 48 type TrieTree struct { 49 Head *TrieNode 50 } 51 52 type TrieNode struct { 53 Value byte 54 Brother *TrieNode 55 Child *TrieNode 56 } 57 58 func (tree *TrieTree) Init() { 59 if tree.Head != nil { 60 return 61 } 62 63 tree.Head = new(TrieNode) 64 } 65 66 func (node *TrieNode) FindChild(value byte) (bool, *TrieNode) { 67 if node == nil { 68 return false, nil 69 } 70 71 q := node.Child 72 p := node.Child 73 for p != nil { 74 if value == p.Value { 75 return true, p 76 } 77 q = p 78 p = p.Brother 79 } 80 81 return false, q 82 } 83 84 func (node *TrieNode) AddBrother(value byte) { 85 if node == nil { 86 return 87 } 88 n := new(TrieNode) 89 n.Value = value 90 91 node.Brother = n 92 } 93 94 func (node *TrieNode) AddChild(value byte) { 95 if node == nil { 96 return 97 } 98 n := new(TrieNode) 99 n.Value = value 100 101 node.Child = n 102 } 103 104 func (tree *TrieTree) AddWord(word string) { 105 n := len(word) 106 node := tree.Head 107 for i := 0; i < n; i++ { 108 if node.Child == nil { 109 node.AddChild(word[i]) 110 node = node.Child 111 } else { 112 find, p := node.FindChild(word[i]) 113 if find == false { 114 p.AddBrother(word[i]) 115 p = p.Brother 116 } 117 node = p 118 } 119 } 120 } 121 122 func (tree *TrieTree) FindWord(word string) bool { 123 n := len(word) 124 node := tree.Head 125 for i := 0; i < n; i++ { 126 find, p := node.FindChild(word[i]) 127 if find == false { 128 return false 129 } 130 node = p 131 } 132 return true 133 }
标签:
原文地址:http://www.cnblogs.com/yin3072114/p/5383469.html