实现 Trie (前缀树)(Java算法每日一题)

问:请你实现 Trie 类:

Trie() 初始化前缀树对象。
void insert(String word) 向前缀树中插入字符串 word 。
boolean search(String word) 如果字符串 word 在前缀树中,返回 true(即,在检索之前已经插入);否则,返回 false 。
boolean startsWith(String prefix) 如果之前已经插入的字符串 word 的前缀之一为 prefix ,返回 true ;否则,返回 false 。
例:
输入
[“Trie”, “insert”, “search”, “search”, “startsWith”, “insert”, “search”]
[[], [“apple”], [“apple”], [“app”], [“app”], [“app”], [“app”]]
输出
[null, null, true, false, true, null, true]
原题链接:https://leetcode.cn/problems/implement-trie-prefix-tree/

答:

class Trie {
    private boolean flag;//定义一个boolean类型来判断是否是单词的末尾
    private Trie[] children;//指向子节点的指针数组

    /** Initialize your data structure here. */
    public Trie() {
        children = new Trie[26];//26个节点代表26个小写字母 a-z
        flag = false;//默认flag是false
    }
    
    /** Inserts a word into the trie. */
    public void insert(String word) {
        Trie node = this;
        for(int i = 0;i < word.length();i++)
        {
            int index = word.charAt(i) - 'a';//单词都是a-z
            if(node.children[index] == null)//如果没有这个子节点的话就新建一个子节点
            {
                node.children[index] = new Trie();
            }
            node = node.children[index];//如果有就插入
        }
        node.flag = true;//循环结束,整个单词插入完成
    }
    
    /** Returns if the word is in the trie. */
    public boolean search(String word) {//函数返回boolean类型,所以再重新定义一个函数作为调用
        Trie node = search1(word);
        if(node != null && node.flag == true )//如果节点不是null并且单词已经到末尾
            return true;
        else
            return false;
        
    }
    public Trie search1(String word)
    {
        Trie node = this;
        for(int i = 0;i < word.length();i++)
        {
            int index = word.charAt(i) - 'a';
            if(node.children[index] == null)
            {
                return null;//如果没有查找返回null
            }
            node = node.children[index];
        }
        return node;//找到就返回

    }
    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        if(search1(prefix)!=null)
            return true;
        else 
            return false;
    }
}

/**
 * Your Trie object will be instantiated and called as such:
 * Trie obj = new Trie();
 * obj.insert(word);
 * boolean param_2 = obj.search(word);
 * boolean param_3 = obj.startsWith(prefix);
 */

解析都在代码注释里了,有什么不明白的可以评论一起交流学习~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

万家林

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

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

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

打赏作者

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

抵扣说明:

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

余额充值