实现前缀树 Implement Trie (Prefix Tree)

本文介绍如何实现字典树(Trie),一种用于高效检索字符串集合中元素的数据结构。字典树能有效支持插入、搜索及前缀匹配等操作。文中详细解释了字典树的三个核心特性,并提供了三种不同的实现方案,包括使用HashMap存储子节点、使用数组存储子节点以及将TrieNode作为内部类。

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

问题:

Implement a trie with insertsearch, and startsWith methods.

Note:
You may assume that all inputs are consist of lowercase letters a-z.

解决:https://www.cnblogs.com/grandyang/p/4491665.html

【题意】实现字典树(前缀树),这道题让我们实现一个重要但又有些复杂的数据结构-字典树, 又称前缀树或单词查找树,例如,一个保存了8个键的trie结构,"A", "to", "tea", "ted", "ten", "i", "in", and "inn".如下图所示:

字典树主要有如下三点性质:

1. 根节点不包含字符,除根节点以外每个节点只包含一个字符

2. 从根节点到某一个节点,路径上经过的字符连接起来,为该节点对应的字符串

3. 每个节点的所有子节点包含的字符串不相同

① 一个字典树的节点应该包含字母,其子节点,以及标记其是否为叶节点的标记位。

class TrieNode{//209ms
    char c;//当前节点的字符
    Map<Character,TrieNode> children = new HashMap<>();//子节点
    boolean isLeaf;//标记是否为叶节点
    public TrieNode(){}
    public TrieNode(char c){
        this.c = c;
    }
}
public class Trie{
    private TrieNode root;
    public Trie(){
        root = new TrieNode();//初始化根节点
    }
    public void insert(String word){
        Map<Character,TrieNode> cur = root.children;//获取根节点的子节点,从它开始加入
        for (int i = 0;i < word.length() ;i ++ ) {
            char c = word.charAt(i);
            TrieNode tmp;
            if (cur.containsKey(c)) {
                tmp = cur.get(c);//获取插入的节点
            }else{
                tmp = new TrieNode(c);
                cur.put(c,tmp);
            }
            cur = tmp.children;
            if (i == word.length() - 1) {
                tmp.isLeaf = true;
            }
        }
    }
    public boolean search(String word){
        TrieNode tmp = searchNode(word);//查找前缀,并返回叶节点
        if (tmp != null && tmp.isLeaf) {
            return true;
        }else{
            return false;
        }
    }
    public boolean startsWith(String prefix){
        if (searchNode(prefix) == null) {
            return false;
        }else{
            return true;
        }
    }
    public TrieNode searchNode(String str){//查找前缀
        Map<Character,TrieNode> cur = root.children;
        TrieNode tmp = null;
        for (int i = 0;i < str.length() ;i ++ ) {
            char c = str.charAt(i);
            if (cur.containsKey(c)) {
                tmp = cur.get(c);
                cur = tmp.children;
            }else{
                return null;
            }
        }
        return tmp;
    }
}

/**
 * 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);
 */

② 使用数组提高性能。

每个trie节点只能包含'a' - 'z'字符。 所以我们可以使用一个数组来存储这个字符。

class TrieNode{//174ms
    TrieNode[] children;//每个节点用一个大小为26的数组表示,因为小写字母范围为a-z
    boolean isLeaf;
    public TrieNode(){
        children = new TrieNode[26];//初始化节点
    }
}
public class Trie{
    private TrieNode root;
    public Trie(){
        root = new TrieNode();//初始化根节点
    }
    public void insert(String word){
        TrieNode cur = root;
        for (int i = 0;i < word.length() ;i ++ ) {
            char c = word.charAt(i);
            int index = c - 'a';
            if (cur.children[index] != null) {
                cur = cur.children[index];
            }else{
                TrieNode tmp = new TrieNode();
                cur.children[index] = tmp;
                cur = tmp;
            }
        }
        cur.isLeaf = true;
    }
    public boolean search(String word){
        TrieNode tmp = searchNode(word);//查找前缀,并返回最后一个字符所在的节点
        if (tmp != null && tmp.isLeaf) {
            return true;
        }
        return false;
    }
    public boolean startsWith(String prefix){
        if (searchNode(prefix) == null) {
            return false;
        }else{
            return true;
        }
    }
    public TrieNode searchNode(String str){
        TrieNode cur = root;
        for (int i = 0;i < str.length() ;i ++ ) {
            char c = str.charAt(i);
            int index = c - 'a';
            if (cur.children[index] != null) {
                cur = cur.children[index];
            }else{
                return null;
            }
        }
        if (cur == root) {
            return null;
        }
        return cur;
    }
}
/**
 * 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);
 */

③ 将TrieNode作为内部类。

class Trie{ //160ms
    class TrieNode{
        TrieNode[] children;
        boolean isLeaf;
        public TrieNode(){
            children = new TrieNode[26];
            isLeaf = false;
        }
    }
    private TrieNode root;
    public Trie(){
        root = new TrieNode();
    }
    public void insert(String word){
        TrieNode cur = root;
        char[] wchar = word.toCharArray();
        for (int i = 0;i < word.length() ;i ++ ) {
            if (cur.children[wchar[i] - 'a'] != null) {
                cur = cur.children[wchar[i] - 'a'];
            }else{
                TrieNode tmp = new TrieNode();
                cur.children[wchar[i] - 'a'] = tmp;
                cur = tmp;
            }
        }
        cur.isLeaf = true;
    }
    public boolean search(String word){
        char[] wchar = word.toCharArray();
        TrieNode cur = root;
        for (int i = 0;i < word.length() ;i ++ ) {
            if (cur.children[wchar[i] - 'a'] == null) {
                return false;
            }else{
                cur = cur.children[wchar[i] - 'a'];
            }
        }
        return cur.isLeaf;
    }
    public boolean startsWith(String word){
        if (word.length() == 0) {
            return true;
        }
        char[] wchar = word.toCharArray();
        TrieNode cur = root;
        for (int i = 0;i < word.length() ;i ++ ) {
            if (cur.children[wchar[i] - 'a'] == null) {
                return false;
            }else{
                cur = cur.children[wchar[i] - 'a'];
            }
        }
        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);
 */

转载于:https://my.oschina.net/liyurong/blog/1575034

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值