208. 实现 Trie (前缀树)

本文详细介绍了一种高效的数据结构——Trie(前缀树)的实现方法,包括insert、search和startsWith三个核心操作。通过具体示例展示了如何利用Trie存储和查找字符串,以及如何判断是否存在以特定前缀开头的单词。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题

实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作。

例子

在这里插入图片描述

思路
在这里插入图片描述
在这里插入图片描述
children[0] 存 a, children[1] 存 b, children[2] 存 c… 依次类推。所以存的时候我们用当前字符减去 a ,从而得到相应的 children 下标。

  • 方法1
    $$

    $$

    统计每个单词出现的次数,代码的话只需要将 flag 改成 int 类型,然后每次插入的时候计数即可。

  • 方法2
    $$

    $$

代码

//方法1
class Trie {
    class TrieNode {
        TrieNode[] children = new TrieNode[26];
        //是否以该结点为结尾
        boolean flag = false;
        public TrieNode(){
            
        }
    }

    /** Initialize your data structure here. */
    TrieNode root = new TrieNode();
    public Trie() {
         
    }
    
    /** Inserts a word into the trie. */
    public void insert(String word) {
        TrieNode cur = root;
        for(int i=0; i<word.length(); i++){
            
            //如果字符不在trie树中,新建结点
            if(cur.children[word.charAt(i)-'a']==null)
                cur.children[word.charAt(i)-'a'] = new TrieNode();
            
            cur = cur.children[word.charAt(i)-'a'];
        }
        
        cur.flag = true;
    }
    
    /** Returns if the word is in the trie. */
    public boolean search(String word) {
        TrieNode cur = root;
        for(int i=0; i<word.length(); i++){
            if(cur.children[word.charAt(i)-'a']==null) return false;
            
            cur = cur.children[word.charAt(i)-'a'];
        }
        return cur.flag==true;
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        TrieNode cur = root;
        for(int i=0; i<prefix.length(); i++){
            if(cur.children[prefix.charAt(i)-'a']==null) return false;
            
            cur = cur.children[prefix.charAt(i)-'a'];
        }
        return true;
    }
}

//方法2

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值