Sunny-117 / js-challenges

✨✨✨ Challenge your JavaScript programming limits step by step

Home Page:https://juejin.cn/column/7244788137410560055

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

实现 Trie (前缀树)

Sunny-117 opened this issue · comments

commented
// 三种方法 insert search startsWith
const Trie = function() {
    this.root = new TrieNode()
}

const TrieNode = function(){
    //  当前节点的子节点,键值对方式存储
    this.next = {}
    //  当前是否是结束节点
    this.isEnd = false
}


// 插入
Trie.prototype.insert = function(word){
    if(!word) return false
    let node = this.root
    // 遍历word
    for(let i=0;i<word.length;i++){
        node.next[word[i]] = node.next[word[i]]||new TrieNode()
        node = node.next[word[i]]
    }
    node.isEnd = true
    return true
}

// 搜索
Trie.prototype.search = function(word){
    if(!word) return false
    let node = this.root
    for(let i = 0;i<word.length;i++){
        if(node.next[word[i]]){
            node = node.next[word[i]]
        }else {
            return false
        }
    }
    // 树里有appleTree,搜索apple应该返回false,因为e不是最后一个节点
    return node.isEnd
}

// 前缀匹配
Trie.prototype.startsWith = function(prefix){
    if(!prefix) return false
    let node = this.root
    for(let i=0;i<prefix.length;i++){
        if(node.next[prefix[i]]){
            node = node.next[prefix[i]]
        } else {
            return false
        }
    }
    return true
}