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

自学Java day53 使用jvav实现 字典树 数据结构 从jvav到架构师

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

自学Java day53 使用jvav实现 字典树 数据结构 从jvav到架构师

        字典树又称单词查找树,Trie树,是一种树形结构,是一种哈希树的变种。典型应用是用于统计,排序和保存大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。它的优点是:利用字符串的公共前缀来减少查询时间,最大限度地减少无谓的字符串比较,查询效率比哈希树高。

        jvav 实现代码如下

public class Trie {
    private Node root;

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

    //添加字符串string
    void insert(String string) {
        if (string == null) return;
        char[] str = string.toLowerCase().toCharArray();
        Node node = root;
        node.p++;
        int index = 0;
        for (int i = 0; i < str.length; i++) {
            index = str[i] - 'a';
            if (node.next[index] == null) node.next[index] = new Node();
            node.next[index].p++;
            node = node.next[index];
        }
        node.e++;
    }

    //有几个字符串string
    int search(String string) {
        if (string == null) return -1;
        //if (root.p == 0) return -2;
        char[] str = string.toLowerCase().toCharArray();
        Node node = root;
        int index = 0;
        for (int i = 0; i < str.length; i++) {
            index = str[i] - 'a';
            //if (node.next[index] == null || node.next[index].p == 0) return 0;
            if (node.next[index] == null) return 0;
            node = node.next[index];
        }
        return node.e;
    }

    //有几个字符串以string开头
    int prefix(String string) {
        if (string == null) return -1;
        //if (root.p == 0) return -2;
        char[] str = string.toLowerCase().toCharArray();
        Node node = root;
        int index = 0;
        for (int i = 0; i < str.length; i++) {
            index = str[i] - 'a';
            //if (node.next[index] == null || node.next[index].p == 0) return 0;
            if (node.next[index] == null) return 0;
            node = node.next[index];
        }
        return node.p;
    }

    //删除字符串string
    boolean delete(String string) {
        if (search(string) < 1) return false;
        char[] str = string.toLowerCase().toCharArray();
        Node node = root;
        int index = 0;
        node.p--;
        for (int i = 0; i < str.length; i++) {
            index = str[i] - 'a';
            if (--node.next[index].p == 0) {
                node.next[index] = null;
                return true;
            }
            node = node.next[index];
        }
        node.e--;
        return true;
    }
}

class Node {
    public int p;
    public int e;
    public Node[] next;

    public Node() {
        p = 0;
        e = 0;
        next = new Node[26];
    }
}

        此数据结构可用于储存任意26个字母组成的字符串,并实现增删查,查前缀功能。

世界线回溯,从jvav到架构师

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

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

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