再战leetcode(208.实现Tire(前缀树)

208.实现Tire(前缀树)

题目描述

在这里插入图片描述

题解

具体请看 leetcode大佬题解

代码:

    class TrieNode {
        boolean isWord;//是否是单词
        TrieNode[] children;//26个小写字母

        public TrieNode() {
            isWord = true;
            children = new TrieNode[26];
        }
    }

    public class Trie {
        //根节点,根节点是不存储任何字母的,从根节点的
        //子节点开始存储
        private TrieNode root;

        public Trie() {
            root = new TrieNode();
        }

        //插入字符串
        public void insert(String word) {
            TrieNode current = root;
            for (int i = 0; i < word.length(); i++) {
                int index = word.charAt(i) - 'a';
                //判断字符有没有创建,如果没有创建就创建
                if (current.children[index] == null) {
                    current.children[index] = new TrieNode();
                    //中间的字符不是完整的单词
                    current.children[index].isWord = false;
                }
                current = current.children[index];
            }
            //最后一个字符才能构成一个完整的单词
            current.isWord = true;
        }

        public boolean search(String word) {
            TrieNode current = find(word);
            return current != null && current.isWord;
        }

        public boolean startsWith(String prefix) {
            return find(prefix) != null;
        }

        private TrieNode find(String str) {
            TrieNode current = root;
            int length = str.length();
            for (int i = 0; i < length; i++) {
                int index = str.charAt(i) - 'a';
                if ((current = current.children[index]) == null)
                    return null;
            }
            return current;
        }
    }

作者:sdwwld
链接:https://leetcode-cn.com/problems/implement-trie-prefix-tree/solution/shu-ju-jie-gou-he-suan-fa-zi-dian-shu-de-6t43/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值