LeetCode 热题100-62-Trie(前缀树)

本文详细介绍了如何使用26叉树(字典树)实现插入、搜索和查找前缀的功能。每个节点包含一个26长度的数组,用于存储对应字母的子节点。在插入和查找过程中,通过字符与'a'的差值得到索引,从而高效地遍历树结构。此数据结构在字符串搜索和字典构建中非常实用。
摘要由CSDN通过智能技术生成

核心思想:26叉树
思路:
前缀树,又称字典树。
每个节点创建一个26长度的数组,数组索引index对应字母,0对应a,1对应b,2对应c…。
插入时,如果不存在,则为该节点创建一个26长度的数组(即children不为null),存在,则探索下一个节点。
查找时,则就按照待查找字符串,一位一位的进行查找,通过char-‘a’获取index,比较children是否为空。
查找前缀和查找同理。
简言之,对应索引位置Trie数组是否为空,就是字母是否存在的意思。

class Trie {
    private Trie[] children;
    private boolean isEnd;

    public Trie() {
        children = new Trie[26];
        isEnd = false;
    }
    
    public void insert(String word) {
    	//this是根节点
        Trie node = this;
        for(int i = 0; i < word.length(); i++){
            char ch = word.charAt(i);
            int index = ch - 'a';
            if(node.children[index] == null){
                node.children[index] = new Trie();
            }
            node = node.children[index];
        }
        node.isEnd = true;
    }
    
    public boolean search(String word) {
        Trie node = searchPrefix(word);
        return node != null && node.isEnd;
    }
    
    public boolean startsWith(String prefix) {
        return searchPrefix(prefix) != null;
    }

    public Trie searchPrefix(String prefix){
        Trie node = this;
        for(int i = 0; i < prefix.length(); i++){
            char ch = prefix.charAt(i);
            int index = ch - 'a';
            if(node.children[index] == null){
                return null;
            }
            node = node.children[index];
        }
        return node;
    }
}

/**
 * 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、付费专栏及课程。

余额充值