实现Trie(前缀树)

题目题目

/**
 * 前缀树的实现
 *
 * 一共26个英文字母
 * 
 * 每个英文字符都是一个Trie结点,Trie的子节点为children 
 * 一共有26个子节点,用数组存储
 */
class Trie {

    private Trie[] children;
    private boolean isEnd;

    /** Initialize your data structure here. */
    public Trie() {
        children = new Trie[26];
        isEnd = false;
    }


    /** Inserts a word into the trie. */
    public void insert(String word) {
        Trie node = this;
        char[]  charArr = word.toCharArray();
        for (char aCharArr : charArr) {
            int index = aCharArr - 'a';
            if (node.children[index] == null) {
                node.children[index] = new Trie();
            }
            node = node.children[index];
        }
        node.isEnd = true;
    }

    /**
     * 从字典树的根开始,查找前缀。
     *
     * 对于当前字符对应的子节点,有两种情况:
         子节点存在。沿着指针移动到子节点,继续搜索下一个字符。
         子节点不存在。说明字典树中不包含该前缀,返回空指针。
         重复以上步骤,直到返回空指针或搜索完前缀的最后一个字符。
             存在则返回   true ;
             不存在则返回 false;
     * */
    public boolean search(String word) {
        Trie node = searchPrefix(word);
        return  node!=null && node.isEnd;
    }

    /**
     * 搜索前缀
     * @param prefix 前缀
     * @return 结点
     */
    private Trie searchPrefix(String prefix){
        Trie node = this;
        char[] charArr = prefix.toCharArray();
        for(char item:charArr){
            int index = item-'a';
            if(node.children[index]!=null){
                node = node.children[index];
            }else{
                return null;
            }
        }
        return node;
    }
    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        Trie node = searchPrefix(prefix);
        return  node!=null;
    }
}

/**
 * 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);
 */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值