LeetCode208. 实现 Trie (前缀树)

场景引入

● 给定一个数组:【goo,gi,google,goye,hi,hello】
● 要在数组中查询到前缀为go的元素

如果暴力查询是否存在某个前缀的话:

时间复杂度为: 数组长度*前缀词的长度

下面引出前缀树,来优化解决前缀匹配问题

在这里插入图片描述


注意:

  • 前缀树的实际上属于子节点有多个的一颗树
  • 在每个节点上同时需要记录当前位置的flag的值,(当指针遍历到当前flag时,若之前完全匹配,若此时flag为true则匹配到了完整的单词,若为false,说明仅仅只是词的前缀)

作用:

  • 词频统计
  • 前缀匹配

例题:
在这里插入图片描述

代码实现:

class Trie {
    class TrieNode {
        boolean end;
        TrieNode[] children = new TrieNode[26];
    }

    TrieNode root;

    public Trie() {
        root=new TrieNode();
    }
    
    public void insert(String word) {
        TrieNode temp=root;
        for(char c:word.toCharArray()){
            int x=c-'a';
            if(temp.children[x]==null) temp.children[x]=new TrieNode();
            temp=temp.children[x];
        }
        temp.end=true;
    }
    
    public boolean search(String word) {
        TrieNode temp=root;
        for(char c:word.toCharArray()){
            int x=c-'a';
            if(temp.children[x]==null) return false;
            temp=temp.children[x];
        }
        return temp.end;
    }
    
    public boolean startsWith(String prefix) {
        TrieNode temp=root;
        for(char c:prefix.toCharArray()){
            int x=c-'a';
            if(temp.children[x]==null) return false;
            temp=temp.children[x];
        }
        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);
 */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值