字典树(Trie)

字典树(trie)


在leetcode 上刷题遇到的一种数据结构,以前没听说过,怪我孤陋寡闻,经过了解发现应用还是很广的。觉得有必要记录下

<a href = "https://leetcode.com/problems/implement-trie-prefix-tree/"> leetcode 208</a>
<a href = "https://zh.wikipedia.org/wiki/Trie">Trie的维基百科介绍</a>

  • 概念
  • 根节点不包含字符串
  • 从根节点到某一叶子节点,路径上组成的所有字符就是该节点对应的字符串
  • 每个节点的公共前缀作为一个字符节点保存
  • 应用
  • 词频统计:比hash或者堆要节省空间,
  • 前缀匹配:前缀匹配的算法复杂度是O(1), 要查找匹配前缀字符串的长度

实现


class TrieNode{
    TrieNode[] childs = new TrieNode[26]; // a-z
    int count; //frequence;
    char prefix; //当前节点的字符前缀
    public TrieNode(char prefix){
        this.prefix = prefix; 
        count = 1; //root 的count 初始化为0,所以要
    }
    public TrieNode(){}
    public void addCount(){
        this.count++;
    }
    public void setPrefix(char prefix){
        this.prefix = prefix;
    }
}

public class Trie {
    private TrieNode root;

    public Trie() {
         root = new TrieNode();
    }

    public void insert(String word) {
        TrieNode searchNode = root;
        for (int level = 0;level < word.length();level++){
            char currentChar = word.charAt(level);
            TrieNode node = searchNode.childs[currentChar-'a'];
            if (searchNode.childs[currentChar-'a'] == null)      //如果这个前缀的还是null,那么新建插入一个
                searchNode.childs[currentChar-'a'] = new TrieNode(currentChar);
            else
                node.count++;
            searchNode = searchNode.childs[currentChar-'a'];
        }
    }

    public boolean search(String word) {
        TrieNode searchNode = root;
        for (int level = 0;level < word.length();level++){
            char currentChar = word.charAt(level);
            TrieNode node = searchNode.childs[currentChar-'a'];
            if (node == null)
                return false;
            searchNode = node;
        }
        int childCount = 0;
        for (TrieNode trieNode : searchNode.childs){
            if (trieNode == null)
                continue;
            childCount += trieNode.count;
        }
        return searchNode.count > childCount;
    }


    public boolean startsWith(String prefix) {
        TrieNode searchNode = root;
        for (int level = 0;level < prefix.length();level++){
            char currentChar = prefix.charAt(level);
            TrieNode node = searchNode.childs[currentChar-'a'];
            if (node == null)
                return false;
            searchNode = node;
        }
        return true;
    }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一,定义 在计算机科学中,trie,又称前缀树或字典树,是一种有序树,用于保存关联数组,其中的键通常是字符串。与二...
    evil_ice阅读 13,597评论 1 3
  • (本文转自百度搜索第一个CSDN博客) 一、知识简介 Trie 的强大之处就在于它的时间复杂度。它的插入和查询时间...
    Alan66阅读 4,282评论 0 0
  • BWA Burrows-Wheeler Aligner作为一个十分出名的alignment软件,在各个生信领域的比...
    栽生物坑里的信息汪阅读 10,258评论 0 5
  • 今天是2017年7月19日,比起刚来到这个陌生城市时的狼狈,现在的我至少可以不用吃饭看别人的脸色,也不用穿着廉价的...
    竹风追月阅读 1,859评论 0 1
  • 告别 那些春天生发的花朵 在秋天已变成了薄薄的寒霜 期间有萦回的水流,和萦回的痛 草间的萤火,亮光只有刹那的微弱 ...
    芃麦子99阅读 1,280评论 0 0