(16)Go實現(xiàn)的trie解答leetcode-208

實現(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)載請注明出處。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。