其他分享
首页 > 其他分享> > 左程云基础班——前缀树

左程云基础班——前缀树

作者:互联网

左程云基础班——前缀树

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

前缀树

标签:node,index,word,前缀,int,基础,nexts,TreeNode,左程
来源: https://blog.csdn.net/weixin_46731597/article/details/123619091