208.實現Trie(字首樹)
阿新 • • 發佈:2021-12-02
208.實現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
求解
var Trie = function() { this.trie = {} }; /** * @param {string} word * @return {void} */ Trie.prototype.insert = function(word) { let tmp = this.trie for(let c of word){ if(!tmp[c]){ tmp[c]={} } tmp = tmp[c] } tmp[1]={} }; /** * @param {string} word * @return {boolean} */ Trie.prototype.search = function(word) { let tmp = this.trie for(let c of word){ if(!tmp[c]){ return false } tmp = tmp[c] } if(!tmp[1]){ return false }else{ return true } }; /** * @param {string} prefix * @return {boolean} */ Trie.prototype.startsWith = function(prefix) { let tmp = this.trie for(let c of prefix){ if(!tmp[c]){ return false } tmp = tmp[c] } 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) */