Trie 前缀树/字典树/单词查找树(数据结构)

前言

在写完了KMP算法的博客之后,我下定决心,一定要写出一篇关于“AC自动机的博客”。AC自动机实际上就是字典树上的KMP算法。所以,考虑到广大同学不一定会写Trie树,特此在此处写了一篇文章介绍介绍这种数据结构。

1.字典树的外貌

(字典树)又称单词查找树,Trie树,是一种树形结构,是一种哈希树的变种。典型应用是用于统计,排序和保存大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。它的优点是:利用字符串的公共前缀来减少查询时间,最大限度地减少无谓的字符串比较,查询效率比哈希树高。——360百科

看下面一张图:

一棵字典树

这棵字典树所表示的字符串集合为{ a , to , tea , ted , ten , i , in , inn }。其中每一个被染色的结点都是一个单词的结尾,表示从根节点到当前结点所走过的的路径是一个储存的字符串。我们被染色的结点中储存它所对应的字符串的信息。这就好像是一个字典,我可以在一个字符串所对应的结点中储存这个单词的定义、用法、以及其它信息(附加信息:i结点的附加信息用val[i]表示)。val[i]>0表示这是一个单词,val[i]=0表示这个结点不是一个单词的结尾。

我们用next[i][j]表示,i的第j个儿子。假设这个trie树中的所有字母都是小写字母,那么我们可以用j=0表示标有小写字母‘a’的边,j=25表示标有小写字母‘z’的边。用这条性质,我们可以尝试着去写一下代码。

接下来是字典树的结点用结构体的表示:

int idx(char c)//用于返回一个字符的索引值
{
    return c-'a';
}
struct Trie
{
    int next[MaxNode][26];//结点的权值
    int val[MaxNode];//所有子结点
    int size;//结点总数
    Trie()
    {
        memset(next[0],0,sizeof(next[0]));
    }
    ...//字典树的查询结点和插入结点函数
};

2.字典树的查询结点和插入结点函数

先看一下插入结点的代码:

struct Trie
{
    ...//同上文数据定义部分
    void insert(char* str,int Value)//插入一个字符串,并把附加信息值赋为Value
    {                               //要注意Value!=0
        int nodeNow=0,n=strlen(str);//nodeNow:当前结点,n:字符串的长度
        //0号结点表示字典树的树根
        for(int i=0;i<n;i++)//每次判断字符串中的一个字符
        {
            int charNow=idx(str[i]);//计算这个字符的索引数
            if(next[nodeNow][charNow]==0)//如果这个结点不存在
            {
                next[nodeNow][charNow]=++size;//申请一个新的节点
                memset(next[size],0,sizeof(next[size]));//初始化
                val[size]=0;//因为它是一个过程中的点,而不是字符串的末尾,所以权值为0
            }
            nodeNow=next[nodeNow][charNow];//"当前结点"转移到下一个下一个节点身上
        }
        val[nodeNow]=Value;//把最后找到的末尾结点附上一个属性值
    }
};

然后查询结点的代码和上文是非常像的。

struct Trie
{
    ...//同上文数据定义部分
    int Search(char* str)
    {
        int nodeNow=0,n=strlen(str);
        for(int i=0;i<n;i++)
        {
            int charNow=idx(str[i]);
            if(next[nodeNow][charNow]==0)//如果结点不存在
                return 0;//直接返回0
            nodeNow=next[nodeNow][charNow];//光标移动到下一结点
        }
        return val[nodeNow];//找到之后返回结点的权值
    }
};

3.后记

Trie树是一种简单的数据结构,以上就是它的全部内容。
在学习了Trie树之后,再配合上KMP的算法思想,同学们就可以去进修“AC自动机”算法了。

给一个友情链接:

友情链接1:神奇的KMP——线性时间匹配算法(初学者请进)
友情链接2:我与线段树的故事(纯新手请进)
友情链接3:AC自动机详解

赶稿匆忙,如有谬误,望谅解。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值