算法之前缀树模版

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--;
    }
}
全部评论

相关推荐

认真搞学习:28小登的建议,投算法岗不要写什么物理竞赛,互联网+,多写点项目,用什么算法做了什么。还有本科算法是不可能的开发你这个也没有项目啊
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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