《恋上数据结构第1季》字典树 Trie

简介: 《恋上数据结构第1季》字典树 Trie
数据结构与算法笔记目录《恋上数据结构》 笔记目录

想加深 Java 基础推荐看这个Java 强化笔记目录

我的《恋上数据结构》源码(第1季 + 第2季):https://github.com/szluyu99/Data_Structure_Note

Trie 简介

Trie 也叫做 字典树前缀树(Prefix Tree)单词查找树
Trie 搜索字符串的效率主要跟字符串的长度有关

优点:搜索前缀的效率主要跟前缀的长度有关
缺点:需要耗费大量的内存,因此还有待改进

更多Trie 相关的数据结构和算法:

  • Double-array Trie、Suffix Tree、Patricia Tree、Crit-bit Tree、AC自动机

例:使用 Trie 存储 cat、dog、doggy、does、cast、add 六个单词
在这里插入图片描述

Trie 实现

接口设计

public interface Trie <V> {
    int size(); 
    boolean isEmpty(); 
    void clear(); 
    boolean contains(String str); 
    V add(String str,V value); 
    V remove(String str); 
    boolean starswith(String prefix);
}

源码

/**
 * @author yusael
 * Trie 字典树
 */
public class Trie <V> {
    private int size;
    private Node<V> root;
    
    private static class Node<V>{
        Node<V> parent;
        HashMap<Character, Node<V>> children;
        Character character; // 为删除做准备
        V value;
        boolean word; // 是否为单词的结尾(是否为一个完整的单词)
        public Node(Node<V> parent) {
            this.parent = parent;
        }
    }
    
    public int size(){
        return size;
    }
    
    public boolean isEmpty(){
        return size == 0;
    }
    
    public void clear(){
        size = 0;
        root = null;
    }
    
    public V get(String key){
        Node<V> node = node(key);
        return (node!=null && node.word) ? node.value : null;
    }
    
    public boolean contains(String key){
        Node<V> node = node(key);
        return node!=null && node.word;
    }
    
    public V add(String key, V value){
        keyCheck(key);
        
        // 创建根节点
        if(root == null){
            root = new Node<>(null);
        }
        
        Node<V> node = root;
        int len = key.length();
        for(int i = 0; i < len; i++){
            char c = key.charAt(i);
            boolean emptyChildren = (node.children==null);
            Node<V> childNode = emptyChildren ? null : node.children.get(c);
            if(childNode == null){
                childNode = new Node<>(node);
                childNode.character = c;
                node.children = emptyChildren ? new HashMap<>() : node.children;
                node.children.put(c, childNode);
            }
            node = childNode;
        }
        
        if(node.word){ // 已经存在这个单词
            V oldValue = node.value;
            node.value = value;
            return oldValue;
        }
        
        // 新增一个单词
        node.word = true;
        node.value = value;
        size++;
        return null;
    }
    
    public V remove(String key){
        // 找到最后一个节点
        Node<V> node = node(key);
        // 如果不是单词结尾,不用作任何处理
        if(node==null || !node.word) return null;
        size--;
        V oldValue = node.value;
            
        // 如果还有子节点
        if(node.children!=null && !node.children.isEmpty()){
            node.word = false;
            node.value = null;
            return oldValue; 
        }
        
        // 没有子节点
        Node<V> parent = null;
        while((parent = node.parent) != null){
            parent.children.remove(node.character);
            if(parent.word || !parent.children.isEmpty()) break;
            node = parent;
        }
        return oldValue;
    }
    
    public boolean startsWith(String prefix){
        return node(prefix) != null;
    }
    
    /**
     * 根据传入字符串,找到最后一个节点
     * 例如输入 dog
     * 找到 g
     */
    private Node<V> node(String key){
        keyCheck(key);
        
        Node<V> node = root;
        int len = key.length();
        for(int i = 0; i < len; i++){
            if(node==null || node.children==null || node.children.isEmpty()) return null;
            char c = key.charAt(i);
            node = node.children.get(c);
        }
        return node;
    }
    
    private void keyCheck(String key){
        if(key==null || key.length()==0){
            throw new IllegalArgumentException("key must not be empty");
        }
    }
    
}

测试

public class Main {
    public static void main(String[] args) {
        Trie<Integer> trie = new Trie<>();
        trie.add("cat", 1);
        trie.add("dog", 2);
        trie.add("catalog", 3);
        trie.add("cast", 4);
        trie.add("小码哥", 5);
        System.out.println(trie.size() == 5);
        System.out.println(trie.startsWith("do"));
        System.out.println(trie.startsWith("c"));
        System.out.println(trie.startsWith("ca"));
        System.out.println(trie.startsWith("cat"));
        System.out.println(trie.startsWith("cata"));
        System.out.println(!trie.startsWith("hehe"));
        System.out.println(trie.get("小码哥") == 5);
        System.out.println(trie.remove("cat") == 1);
        System.out.println(trie.remove("catalog") == 3);
        System.out.println(trie.remove("cast") == 4);
        System.out.println(trie.size() == 2);
        System.out.println(trie.startsWith("小"));
        System.out.println(trie.startsWith("do"));
        System.out.println(!trie.startsWith("c"));
    }
}
相关文章
|
6月前
|
存储 搜索推荐 Java
【Trie树数据结构及其应用】
【Trie树数据结构及其应用】
|
4月前
|
存储 搜索推荐 算法
Python高级数据结构——字典树(Trie)
Python高级数据结构——字典树(Trie)
78 2
Python高级数据结构——字典树(Trie)
|
2月前
|
存储
数据结构:Trie树
数据结构:Trie树
35 1
数据结构:Trie树
|
8月前
|
存储 Java
Java数据结构之第十五章、Trie(前缀树/单词查找树)
1.前缀树的概念:前缀树又叫字典树或单词查找树(高效的存储和查找字符串集合的数据结构)。2.3.存储形式:存储的字符串可能:全是 小写字母 或全是 大写字母 或全是 数字 或全是 0和1。它是一棵,每个代表一个,从。字典树的根节点不包含字符,每个子节点代表一个字符,从根节点到任意一个节点所经过的路径上的字符连接起来即为该节点所代表的字符串。每个节点可以存储一个或多个字符串,通常使用一个标志来标记一个节点代表的字符串是否存在。当需要在一组字符串中查找某个字符串时,可以利用字典树来实现高效的查找操作。
45 0
|
存储 Java
力扣208:实现 Trie (前缀树) (Java多种数据结构)
Trie(发音类似 "try")或者说 前缀树 是一种树形数据结构,用于高效地存储和检索字符串数据集中的键。这一数据结构有相当多的应用情景,例如自动补完和拼写检查。
109 0
力扣208:实现 Trie (前缀树) (Java多种数据结构)
|
机器学习/深度学习 数据格式
数据结构(荣誉)实验二 跳表 Trie树
数据结构(荣誉)实验二 跳表 Trie树
53 0
数据结构(荣誉)实验二 跳表 Trie树
|
搜索推荐 索引
【恋上数据结构】基数排序、桶排序、休眠排序
【恋上数据结构】基数排序、桶排序、休眠排序
【恋上数据结构】基数排序、桶排序、休眠排序
|
搜索推荐 索引
【恋上数据结构】计数排序
【恋上数据结构】计数排序
【恋上数据结构】计数排序
|
搜索推荐 索引
【恋上数据结构】希尔排序
【恋上数据结构】希尔排序
【恋上数据结构】希尔排序