数据结构-字典树

字典树用来高效匹配字符串,具体实现如下:

public class Trie { 

    private Node root;
    //单词的数量
    private int size;

    
    //初始化
    public Trie() {
        this.root = new Node();
        this.size = 0;
    }

    //向前缀树中添加一个单词
    public void add(String word) {
        Node cur = root;
        //遍历单词中的每一个字符
        for (int i = 0;i < word.length();i ++) {
            char c = word.charAt(i);
            if (cur.get(c) == null) {
                cur.put(c, new Node());
            }
            cur = cur.get(c);
        }

        //遍历到单词的最后一个字符后,如果当前节点不是结束节点
        //就修单词结束标识符
        if (!cur.isWord) {
            cur.isWord = true;
            size ++;
        }
    }

   //判断释放包含某一个单词
    public boolean contains(String word) {
        if (size == 0) {
            return false;
        }
        Node cur = root;
        for (int i = 0;i < word.length();i ++) {
            char c = word.charAt(i);
            //如果在遍历过程中发现某一个字符中断了,直接返回false
            //即不包含指定的字符
            if (cur.get(c) == null) {
                return false;
            }
            cur = cur.get(c);
        }
        return cur.isWord;
    }

    //查询释放有包含指定前缀的单词
    public boolean isPrefix(String prefix) {
        Node cur = root;
        for (int i = 0;i < prefix.length();i ++) {
            char c = prefix.charAt(i);
            if (cur.get(c) == null) {
                return false;
            }
            cur = cur.get(c);
        }
        return true;
    }


    /**
       定义节点
    */
    private static class Node{
        //标记是不是一个单词的结尾
        public boolean isWord;
        public Map<Character, Node> next;

        //默认不是单词结束的节点
        public Node() {
            this(false);
        }

        public Node(boolean isWord) {
            this.isWord = isWord;
            next =new TreeMap<>();
        }

        public Node get(Character c) {
            return next.get(c);
        }
        public void put(Character c, Node node) {
            next.put(c, node);
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

echo20222022

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值