算法之前缀树模版

package com.zhang.reflection.面试.算法模版.前缀树;
public class 前缀树 {
    private TreeNode root;
    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];
        }
    }
    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++;
    }
    //完整前缀
    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;
    }
    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--;
    }
}
全部评论

相关推荐

点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
06-27 20:15
还能挽救吗?找同学帮忙看了一下&nbsp;字节怎么能如此对我
牛客26396789...:你这是严重红线,被发现你自己永远进不去,你那个同学直接走人,你还敢宣扬
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务