力扣 208. 实现 Trie (前缀树) 字典树

本文详细介绍了如何使用C++实现前缀树(Trie)数据结构,包括插入、搜索和检查前缀匹配等操作。前缀树是一种高效的数据结构,常用于关键词检索和字符串集合的快速查询,其核心在于利用节点间的链接存储字符串,并通过bool标志记录字符串结尾。
摘要由CSDN通过智能技术生成

https://leetcode-cn.com/problems/implement-trie-prefix-tree/
在这里插入图片描述
思路:每个节点存储26个子节点——相当于从小写字母 a a a z z z,我们还需要知道当前节点是否是某个字符串的尾端,由于本题不需要计数,那么用一个 b o o l bool bool值记录即可。

class Trie {
public:
    /** Initialize your data structure here. */
    Trie() {
        child.resize(26,nullptr);
    }
    
    /** Inserts a word into the trie. */
    void insert(const string& word) {
        Trie *cur=this;
        for(char ch:word)
        {
            ch-='a';
            if(!cur->child[ch])
                cur->child[ch]=new Trie();
            cur=cur->child[ch];
        }
        cur->end=true;
    }
    
    /** Returns if the word is in the trie. */
    bool search(const string& word) {
        Trie *cur=this;
        for(char ch:word)
        {
            ch-='a';
            if(cur->child[ch])
                cur=cur->child[ch];
            else
                return 0;
        }
        return cur->end;
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    bool startsWith(const string& prefix) {
        Trie *cur=this;
        for(char ch:prefix)
        {
            ch-='a';
            if(cur->child[ch])
                cur=cur->child[ch];
            else
                return 0;
        }
        return 1;
    }
private:
    vector<Trie*> child;
    bool end=false;
};

/**
 * Your Trie object will be instantiated and called as such:
 * Trie* obj = new Trie();
 * obj->insert(word);
 * bool param_2 = obj->search(word);
 * bool param_3 = obj->startsWith(prefix);
 */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值