0
点赞
收藏
分享

微信扫一扫

左程云基础班——前缀树

Separes 2022-03-20 阅读 106
java算法

左程云基础班——前缀树

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)示图

前缀树

举报

相关推荐

0 条评论