Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

实现 Trie (前缀树) #250

Open
Sunny-117 opened this issue Nov 4, 2022 · 1 comment
Open

实现 Trie (前缀树) #250

Sunny-117 opened this issue Nov 4, 2022 · 1 comment

Comments

@Sunny-117
Copy link
Owner

No description provided.

@z1the3
Copy link

z1the3 commented May 5, 2023

// 三种方法 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
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants