美文网首页
Trie(前缀树、字典树)

Trie(前缀树、字典树)

作者: 秦汉邮侠 | 来源:发表于2018-03-17 11:01 被阅读142次

定义

  • trie,又称前缀树或字典树,是一种有序树,用于保存关联数组,其中的键通常是字符串。与二叉查找树不同,键不是直接保存在节点中,而是由节点在树中的位置决定。一个节点的所有子孙都有相同的前缀,也就是这个节点对应的字符串,而根节点对应空字符串。一般情况下,不是所有的节点都有对应的值,只有叶子节点和部分内部节点所对应的键才有相关的值。

特点

  • 根节点不包含字符,除根节点外每一个节点都只包含一个字符
  • 从根节点到某一节点,路径上经过的字符连接起来,为该节点对应的字符串
  • 每个节点的所有子节点包含的字符都不相同

复杂度

  • 参数:单词长度(L),树的出度(N),树的高度(M)
  • 时间复杂度:O(L)
  • 空间复杂度:O(N^M)

优点

  • 最大限度地减少无谓的字符串比较,查询效率比较高

应用

  • 词频统计
  • 输入提示

图形表示

  • image

Java实现

class Trie {
    class TrieNode {
        public TrieNode() {
            children = new TrieNode[26];
            is_word = false;
        }
        public boolean is_word;
        public TrieNode[] children;
    }
    
    private TrieNode root;
    
    /** Initialize your data structure here. */
    public Trie() {
        root = new TrieNode();
    }
    
    /** Inserts a word into the trie. */
    public void insert(String word) {
        TrieNode p = root;
        for (int i = 0; i < word.length(); i++) {
            int index = (int)(word.charAt(i) - 'a');
            if (p.children[index] == null)
                p.children[index] = new TrieNode();
            p = p.children[index];
        }
        p.is_word = true;
    }
    
    /** Returns if the word is in the trie. */
    public boolean search(String word) {
        TrieNode node = find(word);
        return node != null && node.is_word;
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        TrieNode node = find(prefix);
        return node != null;
    }
    
    private TrieNode find(String prefix) {
        TrieNode p = root;
        for(int i = 0; i < prefix.length(); i++) {
            int index = (int)(prefix.charAt(i) - 'a');
            if (p.children[index] == null) return null;
            p = p.children[index];
        }
        return p;
    }
}

参考来源

相关文章

  • 前缀树(字典树/Trie)Java实现和应用

    摘要: 前缀树,字典树,插入查询逻辑,Java实现,时间复杂度分析 前缀树介绍 Trie树又被称为前缀树、字典树,...

  • AC自动机学习笔记

    先简单复习一下学习AC自动机所需要的前缀知识。 前缀知识 1-Trie树 字典树,也称Trie树,前缀树,主要用于...

  • 以太坊详解 之 Merkle Patricia Tree

    基础知识 Trie树 Trie是一种搜索树,又称字典树(digital tree)和前缀树(prefix tree...

  • 【 数据结构 & 算法 】—— 高级数据结构

    思维导图 1/3:trie树(字典树)的基础知识 trie树,又称字典树或前缀树,是一种有序的、用于统计、排序和存...

  • trie树

    文章内容来自 Trie树:应用于统计和排序Trie树 trie树又称:字典树、单词查找树、前缀树等,总之是一种树状...

  • 1:Trie树(字典树)

    1:Trie树,也可以叫字典树、前缀树 http://www.cnblogs.com/huangxincheng/...

  • 数据结构之Trie字典树

    什么是Trie字典树 Trie 树,也叫“字典树”或“前缀树”。顾名思义,它是一个树形结构。但与二分搜索树、红黑树...

  • 数据结构与算法(十一)Trie字典树

    本文主要包括以下内容: Trie字典树的基本概念 Trie字典树的基本操作插入查找前缀查询删除 基于链表的Trie...

  • 数据结构与算法(第一季):Trie

    一、概念 Trie 也叫做字典树、前缀树(Prefix Tree)、单词查找树。 Trie 搜索字符串的效率主要跟...

  • 数据结构-Trie

    ◼ Trie 也叫做字典树、前缀树(Prefix Tree)、单词查找树◼ Trie 搜索字符串的效率主要跟字符串...

网友评论

      本文标题:Trie(前缀树、字典树)

      本文链接:https://www.haomeiwen.com/subject/ajodqftx.html