剑指offer 专项突破版 62、实现前缀树

本文讲解了如何使用前缀树(Trie)的数据结构进行字符串的高效插入、搜索和起始字符匹配。通过实例演示了TrieNode的定义、初始化Trie结构、insert方法实现、search和startsWith函数的工作原理。
摘要由CSDN通过智能技术生成

题目链接

思路
  • 这个题目就学习一下前缀树的结点的定义方式就好啦~ 因为说了默认只存储小写字母,所以可以用一个长度为26的数组来存储子节点
  • insert函数注意最后要把isWord置为true
  • search函数注意只有最后isWord是true才能返回true
  • startsWith则没有上述要求~
class Trie {
    private class TrieNode {
        TrieNode[] children;
        boolean isWord;

        TrieNode() {
            children = new TrieNode[26];
        }
    }

    private TrieNode root;

    /**
     * Initialize your data structure here.
     */
    public Trie() {
        root = new TrieNode();
    }

    /**
     * Inserts a word into the trie.
     */
    public void insert(String word) {
        TrieNode cur = root;
        for (char ch : word.toCharArray()) {
            if (null == cur.children[ch - 'a'])
                cur.children[ch - 'a'] = new TrieNode();

            cur = cur.children[ch - 'a'];
        }
        cur.isWord = true;
    }

    /**
     * Returns if the word is in the trie.
     */
    public boolean search(String word) {
        TrieNode cur = root;
        for (char ch : word.toCharArray()) {
            if (null == cur.children[ch - 'a'])
                return false;
            cur = cur.children[ch - 'a'];
        }
        return cur.isWord;
    }

    /**
     * Returns if there is any word in the trie that starts with the given prefix.
     */
    public boolean startsWith(String prefix) {
        TrieNode cur = root;
        for (char ch : prefix.toCharArray()) {
            if (null == cur.children[ch - 'a'])
                return false;
            cur = cur.children[ch - 'a'];
        }
        return true;
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值