剑指 Offer II 062. 实现前缀树

本文详细介绍了一个基于Python实现的前缀树(Trie)模板,包括初始化、插入单词、搜索和判断前缀的功能。通过实例演示,理解Trie在字符串操作中的高效性和应用场景,如单词查找、自动补全和字符串匹配。

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

解题思路

  前缀树模板。

代码
class Trie {
    private Trie[] next;
    boolean isEnd;

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

    /**
     * Inserts a word into the trie.
     */
    public void insert(String word) {
        int length = word.length();
        Trie now = this;
        for (int i = 0; i < length; i++) {
            int index = word.charAt(i) - 'a';
            if (now.next[index] == null) {
                now.next[index] = new Trie();
            }
            now = now.next[index];
        }
        now.isEnd = true;
    }

    /**
     * Returns if the word is in the trie.
     */
    public boolean search(String word) {
        int length = word.length();
        Trie now = this;
        for (int i = 0; i < length; i++) {
            int index = word.charAt(i) - 'a';
            if (now.next[index] == null) return false;
            now = now.next[index];
        }
        return now.isEnd;
    }

    /**
     * Returns if there is any word in the trie that starts with the given prefix.
     */
    public boolean startsWith(String prefix) {
        int length = prefix.length();
        Trie now = this;
        for (int i = 0; i < length; i++) {
            int index = prefix.charAt(i) - 'a';
            if (now.next[index] == null) return false;
            now = now.next[index];
        }
        return true;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值