前缀树

一、前缀树定义

1)单个字符串中,字符从前到后的加到一棵多叉树上

2)字符放在边上,节点上有专属的数据项(常见的是pass和end值)

3)样本添加方式,每个字符串都从根节点开始加,如果没有路就新建,如果有路就复用

4)添加时,沿途节点的pass值加1,每个字符串结束时来到的节点end值加1

作用:可以更加方便的完成前缀相关的查询

二、简版的前缀树

只能存放26个小写字母组成的字符串

/**
 * 字符种类:只有26个小写字母
 * 
 * @author Java和算法学习:周一
 */
public static class Node1 {
    // 当前节点被经过了几次
    private int pass;
    // 有多少个字符串以当前节点结尾
    private int end;
    // 当前节点所有的子节点
    private Node1[] nexts;

    // 节点只存放26个小写字母
    public Node1() {
        pass = 0;
        end = 0;
        // node[i] == null,节点不存在
        nexts = new Node1[26];
    }
}

public static class Trie1 {
    private Node1 root;

    public Trie1() {
        root = new Node1();
    }

    /**
     * 向前缀树中添加一个字符串
     */
    public void insert(String word) {
        if (word == null) {
            return;
        }
        // 正在添加字符的节点
        Node1 node = root;
        // 已经有字符经过该节点,修改节点pass值
        node.pass++;
        int path = 0;
        // 当前单词挨个字符的添加到前缀树上
        char[] chars = word.toCharArray();
        for (char aChar : chars) {
            // 当前字符应该走的路径
            path = aChar - 'a';
            // 当前节点的path路径对应节点不存在,则新建
            if (node.nexts[path] == null) {
                node.nexts[path] = new Node1();
            }
            // 当前节点的path路径对应节点肯定已经存在了
            // 所以当前节点来到path路径对应节点
            node = node.nexts[path];
            // 已经有字符到达该节点,修改pass值
            node.pass++;
        }
        // 字符添加完毕,修改最后节点的end值
        node.end++;
    }

    /**
     * word单词之前加过多少次
     */
    public int search(String word) {
        if (word == null) {
            return 0;
        }
        int index = 0;
        char[] chars = word.toCharArray();
        // 从根节点开始找
        Node1 node = root;
        for (char aChar : chars) {
            // 当前字符应该走的路径
            index = aChar - 'a';
            // 当前节点的index路径对应节点不存在,直接返回
            if (node.nexts[index] == null) {
                return 0;
            }
            // 当前节点的index路径对应节点存在,则当前查找节点来到index路径对应节点
            node = node.nexts[index];
        }
        // 最后当前节点的end值即是此单词加过的次数
        return node.end;
    }

    /**
     * 所有已经加入的字符串中,有多少是以pre为前缀的
     */
    public int prefixNumber(String pre) {
        if (pre == null) {
            return 0;
        }
        int index = 0;
        // 从根节点开始找
        Node1 node = root;
        // 挨个字符找
        char[] chars = pre.toCharArray();
        for (char aChar : chars) {
            // 当前字符应该走的路径
            index = aChar - 'a';
            // 当前节点的index路径对应节点不存在,直接返回
            if (node.nexts[index] == null) {
                return 0;
            }
            // 当前节点的index路径对应节点存在,则当前查找节点来到index路径对应节点
            node = node.nexts[index];
        }
        // 最后当前查找节点所处节点的pass值即是以pre为前缀的数量
        return node.pass;
    }

    /**
     * 在前缀树中删除某个字符串
     */
    public void delete(String word) {
        // 字符串存在才执行删除逻辑
        if (search(word) != 0) {
            // 从根节点开始
            Node1 node = root;
            // 修改根节点pass值
            node.pass--;
            int index = 0;
            char[] chars = word.toCharArray();
            for (char aChar : chars) {
                // 当前字符应该走的路径
                index = aChar - 'a';
                // 当前节点index路径对应节点的pass值减一
                if (--node.nexts[index].pass == 0) {
                    // 减一后如果为0,表明没有字符串再经过此节点
                    // 将此节点index路径对应节点置空,帮助GC
                    node.nexts[index] = null;
                    return;
                }
                // 减一后不为0,表明还有字符串经过此节点
                // 则当前节点移动到index路径对应的节点
                node = node.nexts[index];
            }
            // 最后修改节点所在位置end值
            node.end--;
        }
    }

}

三、通用的前缀树

不限定存放的内容

/**
 * 字符种类:不一定只有26个小写字母
 *
 * @author Java和算法学习:周一
 */
public static class Node2 {

    // 当前节点被经过了几次
    private int pass;

    // 有多少个字符串以当前节点结尾
    private int end;

    // 当前节点所有的子节点,Key为节点对应字符串字符转换为整型后的ASCII码值
    private HashMap<Integer, Node2> nexts;

    public Node2() {
        pass = 0;
        end = 0;
        nexts = new HashMap<>();
    }
}

public static class Trie2 {
    private Node2 root;

    public Trie2() {
        root = new Node2();
    }

    /**
     * 向前缀树中添加一个字符串,此字符串不一定全是小写字母
     */
    public void insert(String str) {
        if (str == null) {
            return;
        }
        // 正在添加字符串的节点
        Node2 node = root;
        // 已经有字符经过该节点,修改节点pass值
        node.pass++;
        int index = 0;
        // 当前字符串挨个字符的添加到前缀树上
        char[] chars = str.toCharArray();
        for (char aChar : chars) {
            index = aChar;
            // 当前节点的index路径对应节点不存在,则新建
            if (!node.nexts.containsKey(index)) {
                node.nexts.put(index, new Node2());
            }
            // 当前节点的index路径对应节点已经存在了
            // 所以当前节点来到index路径对应节点
            node = node.nexts.get(index);
            // 已经有字符到达该节点,修改pass值
            node.pass++;
        }
        // 字符串添加完毕,修改最后节点的end值
        node.end++;
    }

    /**
     * 字符串之前加过多少次
     */
    public int search(String str) {
        if (str == null) {
            return 0;
        }
        int index = 0;
        char[] chars = str.toCharArray();
        // 从根节点开始找
        Node2 node = root;
        for (char aChar : chars) {
            // 当前字符应该走的路径
            index = aChar;
            // 当前节点的index路径对应节点不存在,直接返回
            if (!node.nexts.containsKey(index)) {
                return 0;
            }
            // 当前节点的index路径对应节点存在,则当前查找节点来到index路径对应节点
            node = node.nexts.get(index);
        }
        // 最后当前节点的end值即是此字符串加过的次数
        return node.end;
    }

    /**
     * 所有已经加入的字符串中,有多少是以pre为前缀的
     */
    public int prefixNumber(String pre) {
        if (pre == null) {
            return 0;
        }
        int index = 0;
        // 从根节点开始找
        Node2 node = root;
        // 挨个字符找
        char[] chars = pre.toCharArray();
        for (char aChar : chars) {
            // 当前字符应该走的路径
            index = aChar;
            // 当前节点的index路径对应节点不存在,直接返回
            if (!node.nexts.containsKey(index)) {
                return 0;
            }
            // 当前节点的index路径对应节点存在,则当前查找节点来到index路径对应节点
            node = node.nexts.get(index);
        }
        // 最后当前节点的pass值即是以pre为前缀的数量
        return node.pass;
    }

    /**
     * 在前缀树中删除某个字符串
     */
    public void delete(String str) {
        // 字符串存在才执行删除逻辑
        if (search(str) != 0) {
            // 从根节点开始
            Node2 node = root;
            // 修改根节点pass值
            node.pass--;
            int index = 0;
            char[] chars = str.toCharArray();
            for (char aChar : chars) {
                // 当前字符应该走的路径
                index = aChar;
                // 当前节点index路径对应节点的pass值减一
                if (--node.nexts.get(index).pass == 0) {
                    // 减一后如果为0,表明没有字符串再经过此节点
                    // 将此节点index路径对应节点置空
                    node.nexts.remove(index);
                    return;
                }
                // 减一后不为0,表明还有字符串经过此节点
                // 则当前节点移动到index路径对应的节点
                node = node.nexts.get(index);
            }
            // 最后修改节点所在位置end值
            node.end--;
        }
    }

}

以上两种前缀树都只实现了最基本的功能,当实际项目中遇到类似的需求,可以在此基础上添加需要的功能即可,相当于提供了一个模板。

本文所有代码Github获取

你好,周一

6 声望
2 粉丝
0 条评论
推荐阅读
动态规划
前一篇我们仔细聊了聊递归,如果大伙都仔细敲了相关代码,没有收获那是不可能的。同时敏锐的伙伴可能也发现了,接下来我们要说啥了——动态规划,对,终于终于我们聊到动态规划了。

周一pro阅读 742

一文搞懂秒杀系统,欢迎参与开源,提交PR,提高竞争力。早日上岸,升职加薪。
前言秒杀和高并发是面试的高频考点,也是我们做电商项目必知必会的场景。欢迎大家参与我们的开源项目,提交PR,提高竞争力。早日上岸,升职加薪。知识点详解秒杀系统架构图秒杀流程图秒杀系统设计这篇文章一万多...

王中阳Go32阅读 2.4k评论 1

封面图
计算机网络连环炮40问
本文已经收录到Github仓库,该仓库包含计算机基础、Java基础、多线程、JVM、数据库、Redis、Spring、Mybatis、SpringMVC、SpringBoot、分布式、微服务、设计模式、架构、校招社招分享等核心知识点,欢迎star~

程序员大彬14阅读 1.7k

万字详解,吃透 MongoDB!
MongoDB 是一个基于 分布式文件存储 的开源 NoSQL 数据库系统,由 C++ 编写的。MongoDB 提供了 面向文档 的存储方式,操作起来比较简单和容易,支持“无模式”的数据建模,可以存储比较复杂的数据类型,是一款非常...

JavaGuide8阅读 1.6k

封面图
花了半个小时基于 ChatGPT 搭建了一个微信机器人
相信大家最近被 ChatGPT 刷屏了,其实在差不多一个月前就火过一次,不会那会好像只在程序员的圈子里面火起来了,并没有被大众认知到,不知道最近是因为什么又火起来了,而且这次搞的人尽皆知。

Java极客技术12阅读 3.1k评论 3

封面图
数据结构与算法:二分查找
一、常见数据结构简单数据结构(必须理解和掌握)有序数据结构:栈、队列、链表。有序数据结构省空间(储存空间小)无序数据结构:集合、字典、散列表,无序数据结构省时间(读取时间快)复杂数据结构树、 堆图二...

白鲸鱼9阅读 5.2k

PHP转Go实践:xjson解析神器「开源工具集」
我和劲仔都是PHP转Go,身边越来越多做PHP的朋友也逐渐在用Go进行重构,重构过程中,会发现php的json解析操作(系列化与反序列化)是真的香,弱类型语言的各种隐式类型转换,很大程度的减低了程序的复杂度。

王中阳Go11阅读 2.7k评论 4

封面图

你好,周一

6 声望
2 粉丝
宣传栏