栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

字典树及其Java实现

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

字典树及其Java实现

简介:
字典树(Trie)也叫前缀树,是一种树形结构,广泛用于统计和保存大量字符串,利用字符串的公共前缀进行查询,有效提高了字符串的查询速度。

结构:
它是一棵多叉树,规定根节点不存字符,除根节点外,每个子节点仅存一个字符,用Java代码可将其节点定义为这样一个类:

public static class Node {
        public int pass;
        public int end;
        public HashMap child;

        public Node() {
            child = new HashMap<>();
        }
    }

图形上是长这样:

我们平时常见的二叉树每个节点最多只有2个子节点,对于字典树的话子节点的数量是未知的,需要用可以存储多个节点的数据结构来表示,这里用的是map结构,用数组也可以。

操作:
基本操作有插入、查找跟删除。
直接上代码:

public void insert(String word) {
        if (word == null) {
            return;
        }
        char[] chars = word.toCharArray();
        Node node = root;
        node.pass++;
        int index;
        for (int i = 0; i < chars.length; i++) {
            index = chars[i];
            if (!node.child.containsKey(index)) {
                node.child.put(index, new Node());
            }
            node = node.child.get(index);
            node.pass++;
        }
        node.end++;
    }
public int search(String word) {
        if (word == null) {
            return 0;
        }
        char[] chars = word.toCharArray();
        Node node = root;
        int index;
        for (int i = 0; i < chars.length; i++) {
            index = chars[i];
            if (!node.child.containsKey(index)) {
                return 0;
            }
            node = node.child.get(index);
        }
        return node.end;
    }
public int prefixNumber(String pre) {
        if (pre == null) {
            return 0;
        }
        char[] chars = pre.toCharArray();
        Node node = root;
        int index;
        for (int i = 0; i < chars.length; i++) {
            index = chars[i];
            if (!node.child.containsKey(index)) {
                return 0;
            }
            node = node.child.get(index);
        }
        return node.pass;
    }
public void delete(String word) {
        if (search(word) != 0) {
            char[] chars = word.toCharArray();
            Node node = root;
            node.pass--;
            int index;
            for (int i = 0; i < chars.length; i++) {
                index = chars[i];
                if (--node.child.get(index).pass == 0) {
                    node.child.remove(index);
                    return;
                }
                node = node.child.get(index);
            }
            node.end--;
        }
    }

变量名定义的比较清晰,代码逻辑也比较简单,就不啰嗦解释了。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/658317.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号