leetcode208——实现Trie(前缀树)——java实现

题目要求:
在这里插入图片描述
分析:
首先来了解下什么叫前缀树,请参照这篇博客:
数据结构与算法(十一)Trie字典树

字典树的结构如下图所示:
在这里插入图片描述
其中根节点是空的

接下来就来思考如何实现代码。
首先,我们设置一个TrieNode的数据结构,里面包含child和isEnd,它们分别表示子节点(每个节点最多能有26个子节点)和是否是最后一个节点。

在插入word字符串时,从根节点开始。如果根节点的子节点中不包含word字符串的第一个字符,则直接创建一个子节点;如果包含,则就直接指向该子节点,再继续该过程,直到遍历完word字符串为止。当遍历完word字符串之后,我们需要将isEnd置为true,来表示已经插入结束了。

在搜索word字符串时,也从根节点开始。如果根节点的子节点不包含word字符串的第一个字符,就直接返回false,不用做了;如果包含,则指向该子节点,再继续该过程,直到遍历完word字符串为止。当遍历完word字符串之后,需要对isEnd进行判断,如果isEnd为true,则证明确实存在该字符串,返回true;如果isEnd为false,则证明不存在该字符串,返回false。

在判断是否以字符串prefix来start的时候,条件比搜索宽松一点,即:无论isEnd是不是true,它都返回true。

具体代码如下:

class TrieNode {
    TrieNode[] child;
    boolean isEnd;
    public TrieNode() {
        this.child = new TrieNode[26];
        this.isEnd = false;
    }
}

class Trie {
    
    TrieNode root;

    /** Initialize your data structure here. */
    public Trie() {
        root = new TrieNode();
    }
    
    /** Inserts a word into the trie. */
    public void insert(String word) {
        TrieNode p = root;
        for(int i = 0; i < word.length(); i ++) {
            char c = word.charAt(i);
            if(p.child[c - 'a'] == null) {
                p.child[c - 'a'] = new TrieNode();
            }
            p = p.child[c - 'a'];
        }
        p.isEnd = true;
    }
    
    /** Returns if the word is in the trie. */
    public boolean search(String word) {
        TrieNode p = root;
        for(int i = 0; i < word.length(); i ++) {
            char c = word.charAt(i);
            if(p.child[c - 'a'] == null) {
                return false;
            }
            p = p.child[c - 'a'];
        }
        /*if(p.isEnd == true) {
            return true;
        }
        return false;*/
        return p.isEnd;
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        TrieNode p = root;
        for(int i = 0; i < prefix.length(); i ++) {
            char c = prefix.charAt(i);
            if(p.child[c - 'a'] == null) {
                return false;
            }
            p = p.child[c - 'a'];
        }
        return true;
    }
}

/**
 * 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
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值