字典树Trie模板
Python版本
class Trie:
def __init__(self):
self.children = defaultdict(Trie)
self.word = ""
self.is_word = False
def insert(self, word):
cur = self
for w in word:
cur = cur.children[w]
cur.is_word = True
cur.word = word
def search(self, word):
cur = self
for w in word:
if w not in cur.children:
return False
cur = cur.children[w]
return cur.is_word
下面是Golang实现
Golang版本
package main
import (
"fmt"
"strconv"
)
type Trie struct {
Child map[interface{}]*Trie
IsEnd bool
}
func Constructor() Trie {
return Trie{}
}
func (this *Trie) Insert(word string) {
t := this
for _, v := range word {
if t.Child == nil {
t.Child = make(map[interface{}]*Trie)
}
if _, ok := t.Child[v]; !ok {
t.Child[v] = &Trie{}
}
t = t.Child[v]
}
t.IsEnd = true
}
func (this *Trie) Search(word string) bool {
t := this
for index, v := range word {
if t.Child == nil {
return false
}
if _, ok := t.Child[v]; !ok {
return false
}
t = t.Child[v]
if index == len(word)-1 && !t.IsEnd {
return false
}
}
return true
}
func (this *Trie) StartsWith(prefix string) bool {
t := this
for _, v := range prefix {
if t.Child == nil {
return false
}
if _, ok := t.Child[v]; !ok {
return false
}
t = t.Child[v]
}
return true
}
func main() {
word := "he;;p"
obj := Constructor()
obj.Insert(word)
param_2 := obj.Search(word)
fmt.Println(param_2)
prefix := "he;"
param_3 := obj.StartsWith(prefix)
fmt.Println(param_3)
binnum := fmt.Sprintf("%.3f", 7.12)
f, _ := strconv.ParseFloat(binnum, 64)
fmt.Println(f)
mp := make(map[interface{}]interface{})
mp[10] = 10
mp['a'] = 10
mp["ASD"] = func() bool { return false }
fmt.Printf("%T", mp["ASD"])
}

浙公网安备 33010602011771号