”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > Trie简介(前缀树)

Trie简介(前缀树)

发布于2025-02-07
浏览:285

Introduction to Trie (Prefix Tree) Trie

是一种类似树的数据结构,用于有效存储和搜索字符串,尤其是在诸如AutoComplete,Spell Checking和IP路由之类的应用程序中。

Trie的关键特性:


nodes
    :每个节点代表一个字符。
  1. :root节点是空的,并用作起点。
  2. :每个节点最多有26个孩子(用于小写英文字母)或更多,具体取决于字符集。 字标记
  3. :有些节点被标记为指示单词的结尾。
  4. 基本的Trie操作:
  5. 1。 insertion

插入一个单词涉及穿越Trie并为不存在的字符创建新节点。

2。

搜索

搜索通过遍历其节点是否存在一个单词是否存在。

3。

前缀搜索

这检查了三位一体中的任何单词是否从给定的前缀开头。

JavaScript中基本Trie的实现:

类Trienode { constructor(){ this.Children = {}; //存储儿童节点 this.isendofword = false; //标记一个单词的结尾 } } 类Trie { constructor(){ this.root = new Trienode(); } //插入一个单词 插入(word){ 令node = this.root; for(让词字符){ 如果(!node.children [char]){ Node.Children [char] = new Trienode(); } node = node.Children [char]; } node.isendofword = true; //标记单词的结尾 } //搜索一个单词 搜索(Word){ 令node = this.root; for(让词字符){ 如果(!node.children [char]){ 返回false; } node = node.Children [char]; } 返回node.isendofword; } //检查是否有任何单词从给定的前缀开始 startswith(前缀){ 令node = this.root; 对于(让前缀的字符){ 如果(!node.children [char]){ 返回false; } node = node.Children [char]; } 返回true; } } //示例用法 const trie = new trie(); trie.insert(“苹果”); console.log(trie.search(“苹果”)); // 真的 console.log(trie.search(“ app”)); // 错误的 console.log(trie.startswith(“ app”)); // 真的 trie.insert(“ app”); console.log(trie.search(“ app”)); // 真的

高级Trie操作:

1。

删除一个词

class TrieNode {
    constructor() {
        this.children = {}; // Stores child nodes
        this.isEndOfWord = false; // Marks the end of a word
    }
}

class Trie {
    constructor() {
        this.root = new TrieNode();
    }

    // Insert a word
    insert(word) {
        let node = this.root;
        for (let char of word) {
            if (!node.children[char]) {
                node.children[char] = new TrieNode();
            }
            node = node.children[char];
        }
        node.isEndOfWord = true; // Mark the end of the word
    }

    // Search for a word
    search(word) {
        let node = this.root;
        for (let char of word) {
            if (!node.children[char]) {
                return false;
            }
            node = node.children[char];
        }
        return node.isEndOfWord;
    }

    // Check if any word starts with the given prefix
    startsWith(prefix) {
        let node = this.root;
        for (let char of prefix) {
            if (!node.children[char]) {
                return false;
            }
            node = node.children[char];
        }
        return true;
    }
}

// Example usage
const trie = new Trie();
trie.insert("apple");
console.log(trie.search("apple"));   // true
console.log(trie.search("app"));     // false
console.log(trie.startsWith("app")); // true
trie.insert("app");
console.log(trie.search("app"));     // true

2。

用前缀

计数单词:

计数几个单词以给定前缀开头。

[2 令node = this.root; 对于(让前缀的字符){ 如果(!node.children [char])返回0; node = node.Children [char]; } 返回this._countwords(node); } _countwords(node){ 让count = node.isendofword? 1:0; (让char in Node.Children){ count = this._countwords(node.children [char]); } 返回计数; }


3。

autocomplete建议
delete(word, node = this.root, depth = 0) {
    if (depth === word.length) {
        if (!node.isEndOfWord) return false; // Word doesn't exist
        node.isEndOfWord = false;
        return Object.keys(node.children).length === 0; // Check if node has children
    }

    const char = word[depth];
    if (!node.children[char]) return false;

    const shouldDeleteChild = this.delete(word, node.children[char], depth   1);

    if (shouldDeleteChild) {
        delete node.children[char];
        return Object.keys(node.children).length === 0 && !node.isEndOfWord;
    }

    return false;
}

给定前缀,返回所有以其开头的单词。

)返回[]; node = node.Children [char]; } 返回this._collectwords(node,prefix); } _collectwords(node,prefix){ 让结果= []; if(node.isendofword)results.push(prefix); (让char in Node.Children){ 结果= results.concat(this._collectwords(node.children [char],prefix char)); } 返回结果; }


时间复杂性:
countWordsWithPrefix(prefix) {
    let node = this.root;
    for (let char of prefix) {
        if (!node.children[char]) return 0;
        node = node.children[char];
    }
    return this._countWords(node);
}

_countWords(node) {
    let count = node.isEndOfWord ? 1 : 0;
    for (let char in node.children) {
        count  = this._countWords(node.children[char]);
    }
    return count;
}

[2 搜索

:o(l)


prefix search
getWordsWithPrefix(prefix) {
    let node = this.root;
    for (let char of prefix) {
        if (!node.children[char]) return [];
        node = node.children[char];
    }
    return this._collectWords(node, prefix);
}

_collectWords(node, prefix) {
    let results = [];
    if (node.isEndOfWord) results.push(prefix);

    for (let char in node.children) {
        results = results.concat(this._collectWords(node.children[char], prefix   char));
    }

    return results;
}

delete

:o(l)
  1. Trie的申请:
  2. autocomplete systems
  3. (例如,搜索栏,文本编辑器)。
  4. 拼写检查器
  5. [2 Word Games
  6. (例如,boggle)。
[2

版本声明 本文转载于:https://dev.to/keshav___dev/introduction-to-trie-prefix-tree-5g07?1如有侵犯,请联系[email protected]删除
最新教程 更多>

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3