實現(xiàn)代碼
type Trie struct {
isWord bool
next map[rune]*Trie
}
/** Initialize your data structure here. */
func Constructor() Trie {
return Trie{
isWord:false,
next: make(map[rune]*Trie),
}
}
/** Inserts a word into the trie. */
func (this *Trie) Insert(word string) {
if len(word) == 0 {
return
}
cur := this
for _, v := range word {
_, ok := cur.next[v] // 在NewTrie中已經(jīng)初始化
if !ok {
cur.next[v] = &Trie{false, map[rune]*Trie{}}
}
cur = cur.next[v]
}
cur.isWord=true
}
/** Returns if the word is in the trie. */
func (this *Trie) Search(word string) bool {
if len(word) == 0 {
return false
}
cur := this
for _, v := range word {
t1, ok := cur.next[v]
if !ok {
return false
}
cur = t1
}
return cur.isWord
}
/** Returns if there is any word in the trie that starts with the given prefix. */
func (this *Trie) StartsWith(prefix string) bool {
if len(prefix) == 0 {
return true
}
cur := this
for _, v := range prefix {
t1, ok := cur.next[v]
if !ok {
return false
}
cur = t1
}
return true
}
測試通過,由于是用map實現(xiàn)的,所以速度性能一般,map的速度聽別人說比數(shù)組慢100倍
相關(guān):
1)trie解決leetcode-211:添加與搜索單詞
http://www.lxweimin.com/p/74103f51aa36
2)trie解決leetcode-677:鍵值映射
http://www.lxweimin.com/p/dd247d5591a2
有bug歡迎指出,轉(zhuǎn)載請注明出處。