Trie树 学习

前缀树的概述

前缀树又名字典树,单词查找树,Trie树,是hash树的变种,和hash效率有一拼,是一种用于快速检索的多叉树结构。
典型应用是用于统计和排序大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。它的优点是:最大限度地减少无谓的字符串比较,查询效率比哈希表高。

Trie的核心思想是空间换时间。利用字符串的公共前缀来降低查询时间的开销以达到提高效率的目的。
Trie树也有它的缺点,Trie树的内存消耗非常大。
性质:不同字符串的相同前缀只保存一份。
操作:查找,插入,删除

前缀树特性

  • 根节点不包含字符,除根节点外的每一个子节点都包含一个字符
  • 从根节点到某一节点的路径上的字符连接起来,就是该节点对应的字符串
  • 每个节点的所有子节点包含的字符都不相同
  • 每条边对应一个字母。每个节点对应一项前缀。叶节点对应最长前缀,即单词本身。

前缀树的应用场景

  1. 字符串的快速检索
    字典树的查询时间复杂度是O(logL),L是字符串的长度,所以效率高,而且比hash表高,同时支持动态查询
  2. 字符串排序
    单词是排序的,先遍历字母序在前面,减少了没必要的公共子串
  3. 最长公共前缀
  4. 自动匹配前缀显示后缀

前缀树Java实现

class Trie{
    private Trie[] children;
    private boolean isEnd;
    
    public Trie(){
        children = new Trie[26];
        isEnd = false;
    }
    
    public void insert(String word){
        Trie node = this;
        for(int i=0;i<word.length;i++){
            char ch = word.charAt(i);
            int index = ch - 'a';
            if(node.children[index]==null){
                node.children[index] = new Trie();
            }
            node = node.children[index];
        }
        node.isEnd = true;
    }
    
    public boolean search(String word){
       Trie node = searchPrefix(word);
        return node != null && node.isEnd;
    }
    
    public boolean startsWith(String prefix){
        return searchPrefix(prefix) != null;
    }
    
    private Trie searchPrefix(String prefix){
        Trie node = this;
        for(int i=0;i<prefix.length;i++){
            char ch = prefix.charAt(i);
            int index = ch - 'a';
            if(node.children[index] == null){
                return null;
                
            }
            node = node.children[index];
        }
        return node;
    }
}
posted @ 2022-06-30 14:52  快打球去吧  阅读(36)  评论(0)    收藏  举报