天天看點

實作 Trie (字首樹)

Trie(發音類似 "try")或者說 字首樹 是一種樹形資料結構,用于高效地存儲和檢索字元串資料集中的鍵。這一資料結構有相當多的應用情景,例如自動補完和拼寫檢查。

請你實作 Trie 類:

Trie() 初始化字首樹對象。

void insert(String word) 向字首樹中插入字元串 word 。

boolean search(String word) 如果字元串 word 在字首樹中,傳回 true(即,在檢索之前已經插入);否則,傳回 false 。

boolean startsWith(String prefix) 如果之前已經插入的字元串 word 的字首之一為 prefix ,傳回 true ;否則,傳回 false 。

示例:

輸入

["Trie", "insert", "search", "search", "startsWith", "insert", "search"]

[[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]

輸出

[null, null, true, false, true, null, true]

解釋

Trie trie = new Trie();

trie.insert("apple");

trie.search("apple");   // 傳回 True

trie.search("app");     // 傳回 False

trie.startsWith("app"); // 傳回 True

trie.insert("app");

trie.search("app");     // 傳回 True

提示:

1 <= word.length, prefix.length <= 2000

word 和 prefix 僅由小寫英文字母組成

insert、search 和 startsWith 調用次數 總計 不超過 3 * 104 次

/**
 * Initialize your data structure here.
 */

var NodeTree = function(val) {
    this.val = val || null;
    this.children = {}
}
var Trie = function() {
    this.Tree = new NodeTree();
};

/**
 * Inserts a word into the trie. 
 * @param {string} word
 * @return {void}
 */
Trie.prototype.insert = function(word) {
    let now = this.Tree;
     for(let i = 0; i < word.length; i++) {
        now =  (now.children[word[i]] || (now.children[word[i]] = new NodeTree(word[i]))); 
     }
     now.children['end'] = new TreeNode('end') // 結束标記
};

/**
 * Returns if the word is in the trie. 
 * @param {string} word
 * @return {boolean}
 */
Trie.prototype.search = function(word) {
    let now = this.Tree;
    for (let i = 0; i < word.length; i++) {
        now = now.children[word[i]]
        if (!now) {
            return false
        }
    }
    return !!now.children['end']
};

/**
 * Returns if there is any word in the trie that starts with the given prefix. 
 * @param {string} prefix
 * @return {boolean}
 */
Trie.prototype.startsWith = function(prefix) {
    let now = this.Tree;
    for (let i = 0; i < prefix.length; i++) {
        now = now.children[prefix[i]]
        if (!now) {
            return false
        }
    }
    return true
};

/**
 * Your Trie object will be instantiated and called as such:
 * var obj = new Trie()
 * obj.insert(word)
 * var param_2 = obj.search(word)
 * var param_3 = obj.startsWith(prefix)
 */      

繼續閱讀