Trie(字典树)详解与C++实现

参考资料

  1. 甜姨的力扣题解:https://zhuanlan.zhihu.com/p/120150816
  2. 力扣官方题解:https://leetcode-cn.com/problems/implement-trie-prefix-tree/solution/shi-xian-trie-qian-zhui-shu-by-leetcode/
  3. https://leetcode-cn.com/problems/implement-trie-prefix-tree/solution/trie-tree-de-shi-xian-gua-he-chu-xue-zhe-by-huwt/

1.2.资料都是基于Java来对Trie进行实现,3.是c++的实现,原理都介绍的非常棒!

Trie Introduction(介绍字典树)

Trie也叫字典树、前缀树、单词查找树等等,它常用来存储单词(和语种无关),相比于HashMap等操作,Trie能在存储多个具有相同前缀的键时,使用较少的空间。并且Tire树只需要O(M)的时间复杂度,其中M为键长。

下图演示了一个保存8个单词的字典树结构,8个单词分别是:“A”, “to”, “tea”, “ted”, “ten”, “i”, “in”, “inn”。(蓝色节点表示单词的结尾字符)
在这里插入图片描述
【示例来自参考资料1】
说明
root节点为Null;
把从root节点出发到蓝色节点的路径上所表示的字符连接起来,就构成一个单词;
从root节点出发,都是单词列表里某个单词/某些单词的前缀;
如果某个字符串没有出现在这棵树的路径上,那说明其不是所给出单词列表的前缀。


然后相比一般的多叉树,Trie在节点的数据结构设计上也有很多不同。

class Trie{
private:
    bool flag;
    Trie* next[R];
};

其中val表示的是该节点是否为尾节点(是不是对应键的结尾),next[R]表示的是指向R个子节点的链接。比如我们现在要表示英语单词的话,R就为26。
说明
因为flag只用来表示该节点是否为一个单词的结尾,然后next[R]可以看做是指向26个字母的映射表,保存了对于当前节点而言,下一个可能出现的字符链接。所以,上面的图并不是字典树真正的存储形式,我们看下图:

这是一个包含三个单词‘sea’,‘she’,‘sells’的字典树完整形式。
在这里插入图片描述
【示例来自参考资料3】
可以看到,Trie中一般含有大量的空链接。

C++实现

class Trie{
private:
    // 定义节点
    bool flag = false;
    Trie* next[26] = {nullptr};
publicTrie(){}    // 构造函数

    void insert(string word){   // 插入
        Trie* node = this;
        for(int i=0; i<word.length(); i++){
            char c = word[i];
            if(node->next[c-'a']==nullptr){
                node->next[c-'a'] = new Trie();
            }
            node = node->next[c-'a'];
        }
        node->flag = true;  // 单词串的尾节点为true
    }

    bool search(string word){   // 查找单词是否存在Trie中
        Trie* node = this;
        for(int i=0; i<word.length(); i++){
            char c = word[i];
            if(node->next[c-'a']==nullptr)  return false;
            node = node->next[c-'a'];
        }
        return node->flag;  // 如果该节点是串尾节点,则为true
    }

    bool starsWith(string prefix){  //查找前缀
        Trie * node = this;
        for(int i=0; i<prefix.length(); i++){
            char c = prefix[i];
            if(node->next[c-'a']==nullptr)  return false;
            node = node->next[c-'a'];
        }
        return true;
    }
};

说明:
最常用的有三个操作,插入单词、搜索单词是否在字典树中、搜索前缀是否在字典树中。
插入单词:node指向根节点,从单词的第一个字符开始判断,该字符是否在节点指向的字母映射表中出现(不为nullptr空指针),如果没有出现过就创建对应的内存空间,然后node指向对应字母的链接。重复操作,直到该单词全部插入完,再另最后的尾结点node->flag=true()(表示一个单词的结尾)。有点类似链表的插入。
查找单词是否在字典树中:同样,node先指向根节点,然后从单词的第一个字符开始判断,该字符是否在node指向的字母映射表中出现,如果没有出现直接return false,否则node指向对应字母的链接,重复操作,直至单词全部查询完。最后再判断node->flag == true?,如果不为true,则表示并不是单词的结尾(该单词没有出现在字典树中,只是前缀包含了该单词)。
查找前缀是否出现在字典树中 :跟上面查找单词是一样的,只是最后不用再判断flag。


对应的LeetCode练习:LeetCode208. 实现Trie(前缀树)

Trie 应用

  1. 自动补全
    在这里插入图片描述

  2. 拼写检查
    在这里插入图片描述

  3. IP路由
    在这里插入图片描述

  • 5
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Trie字典树的Java代码实现可以分为以下几部分: 1. 定义Trie节点类,包含children数组和isEndOfWord标识,用于表示是否是单词的结尾。 2. 定义Trie类,包含插入、查找和删除操作。 3. 在Trie类中实现插入操作,遍历字符串每一个字符,在Trie中寻找对应节点,如果不存在则新建节点。 4. 在Trie类中实现查找操作,遍历字符串每一个字符,在Trie中寻找对应节点,如果找到最后一个字符对应的节点的isEndOfWord标识为true,则说明字符串是单词。 5. 在Trie类中实现删除操作,遍历字符串每一个字符,在Trie中寻找对应节点,如果找到最后一个字符对应的节点的isEndOfWord标识为true,则将其设为false,并删除空节点。 如果需要完整代码和注释请告诉我。 ### 回答2: Trie字典树)是一种常用的数据结构,用于高效地存储和查找字符串。下面是Trie字典树的Java代码实现,用于返回单词。 ```java class TrieNode { private TrieNode[] children; private boolean isEndOfWord; public TrieNode() { children = new TrieNode[26]; // 字母表的大小为26 isEndOfWord = false; } public void insert(String word) { TrieNode curr = this; for (char c : word.toCharArray()) { if (curr.children[c - 'a'] == null) { curr.children[c - 'a'] = new TrieNode(); } curr = curr.children[c - 'a']; } curr.isEndOfWord = true; } public boolean search(String word) { TrieNode node = searchPrefix(word); return node != null && node.isEndOfWord; } public boolean startsWith(String prefix) { TrieNode node = searchPrefix(prefix); return node != null; } private TrieNode searchPrefix(String prefix) { TrieNode curr = this; for (char c : prefix.toCharArray()) { if (curr.children[c - 'a'] == null) { return null; } curr = curr.children[c - 'a']; } return curr; } } public class Trie { private TrieNode root; public Trie() { root = new TrieNode(); } public void insert(String word) { root.insert(word); } public boolean search(String word) { return root.search(word); } public boolean startsWith(String prefix) { return root.startsWith(prefix); } } public class Main { public static void main(String[] args) { Trie trie = new Trie(); trie.insert("apple"); trie.insert("app"); System.out.println(trie.search("apple")); // 输出:true System.out.println(trie.startsWith("app")); // 输出:true System.out.println(trie.search("banana")); // 输出:false } } ``` 以上代码中,`TrieNode`表示Trie的节点,`Trie`表示Trie的结构。其中`TrieNode`类包含了插入单词、查找单词(完全匹配)以及查找前缀的功能。`Trie`类则是对外提供插入、查找单词和前缀的方法。 在`main`方法中,我们演示了如何使用`Trie`类来插入和查找单词。首先,我们插入了两个单词"apple"和"app"。然后分别调用`search`方法来查找"apple"和"banana",以及`startsWith`方法来查找以"app"开头的单词。最后,打印出对应的结果,即是否找到了对应的单词或前缀。 以上是Trie字典树的Java代码实现,用于返回单词。 ### 回答3: Trie字典树是一种经典的数据结构,用于高效地存储和查找字符串集合。下面是一个基于Java的Trie字典树的代码实现,可以实现返回单词的功能: ```java class TrieNode { private final int ALPHABET_SIZE = 26; private TrieNode[] children; private boolean isEndOfWord; public TrieNode() { children = new TrieNode[ALPHABET_SIZE]; isEndOfWord = false; } } class Trie { private TrieNode root; public Trie() { root = new TrieNode(); } public void insert(String word) { TrieNode current = root; for (int i = 0; i < word.length(); i++) { char ch = word.charAt(i); int index = ch - 'a'; if (current.children[index] == null) { current.children[index] = new TrieNode(); } current = current.children[index]; } current.isEndOfWord = true; } public boolean search(String word) { TrieNode current = root; for (int i = 0; i < word.length(); i++) { char ch = word.charAt(i); int index = ch - 'a'; if (current.children[index] == null) { return false; } current = current.children[index]; } return current != null && current.isEndOfWord; } public List<String> getAllWords() { List<String> result = new ArrayList<>(); TrieNode current = root; StringBuilder sb = new StringBuilder(); getAllWordsUtil(current, sb, result); return result; } private void getAllWordsUtil(TrieNode node, StringBuilder sb, List<String> result) { if (node == null) { return; } if (node.isEndOfWord) { result.add(sb.toString()); } for (int i = 0; i < ALPHABET_SIZE; i++) { if (node.children[i] != null) { sb.append((char)('a' + i)); getAllWordsUtil(node.children[i], sb, result); sb.deleteCharAt(sb.length() - 1); } } } } public class Main { public static void main(String[] args) { Trie trie = new Trie(); String[] words = {"hello", "world", "java", "programming"}; for (String word : words) { trie.insert(word); } List<String> allWords = trie.getAllWords(); System.out.println("All words in trie: " + allWords); } } ``` 上述代码中,TrieNode类表示字典树的节点,包括一个指向子节点的数组和一个标记,用于表示节点是否是某个单词的结尾。Trie类封装了字典树的操作,包括插入单词、查找单词和返回所有单词的功能。在代码的主函数中,我们创建一个Trie对象并插入一些单词,然后调用getAllWords()方法返回字典树中的所有单词。最后,打印出返回的单词列表。 希望以上解答对您有所帮助,如有更多疑问,请继续追问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值