微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

左程云基础班——前缀树

左程云基础班——前缀树

https://www.bilibili.com/video/BV13g41157hK?p=10&share_source=copy_web

1. 前缀树结点

边代表字母,结点存边的信息

	private static class TreeNode {
        public int pass;//经过此结点的边的数量
        public int end;//以此边为结束
        public TreeNode[] nexts;

        public TreeNode() {
            this.pass = 0;
            this.end = 0;
            this.nexts = new TreeNode[26];
        }
    }

2. CURD的实现

定义头结点

private TreeNode root;

1)增加前缀

	public void insert(String word) {
            if (word == null) {
                return;
            }
            char[] chars = word.tochararray();
            TreeNode node = root;
            int index = 0;
            for (int i = 0; i < chars.length; i++) {
                index = chars[i] - 'a';
                if (node.nexts[index] == null) {
                     node.nexts[index] = new TreeNode();
                }
                node = node.nexts[index];
                node.pass++;
            }
            node.end++;
        }

2)查询前缀

	//完整前缀
	public int search(String word) {
            if (word == null) {
                return 0;
            }
            char[] chars = word.tochararray();
            TreeNode node = root;
            int index = 0;
            for (int i = 0; i < chars.length; i++) {
                index = chars[i] - 'a';
                if (node.nexts[index] == null) {
                    return 0;
                }
                node = node.nexts[index];
            }
            return node.end;
        }

3)删除前缀

	public void delete(String word) {
            if (word == null || search(word) == 0) {
                return;
            }
            char[] chars = word.tochararray();
            TreeNode node = root;
            int index = 0;
            for (int i = 0; i < chars.length; i++) {
                index = chars[i] - 'a';
                if (--node.nexts[index].pass == 0) {
                    node.nexts[index] = null;
                    return;
                }
                node = node.nexts[index];
            }
            node.end--;
        }

4)示图

前缀树

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐