字典树(Trie)不懂?看这篇就够了

字典树(Trie)

是一种数据结构。

当出现大量字符串时考虑用字典树或者哈希表。

字典树的实现(C++):

  • 时间复杂度:初始化为 O(1),其余操作为 O(|S|),其中 |S| 是每次插入或查询的字符串的长度。

    空间复杂度:O(∣T∣⋅Σ),其中 |T| 为所有插入字符串的长度之和,Σ 为字符集的大小,一般情况Σ=26。

class Trie {
    private:
    	vector<Trie*>child;	/* 孩子 */
    	boool isEnd;		/* 是否是单词结尾 */
    	/** 返回查找字符串的最后一个字符,可以供seach函数与startswith函数复用*/
    	Trie* seachfix(string prefix) {
            Trie* node = this;
            for(char ch:prefix) {
                if(node->child[ch-'a']==nullptr)
                    return nullptr;
                node = node->child[ch-'a'];
            }
            return node;
        }
    public:
    	/** 构造函数 */
    	Trie() : child(26,nullptr),isEnd(false){}
    
    	/* 插入单词 */
    	void insert(string word) {
            Trie* node = this;
            for(char ch:prefix) {
                if(node->child[ch-'a']==nullptr)
                    node->child[ch-'a']=new Trie();
                node = node->child[ch-'a'];
            }
            node->End = true;
        }
    	
    	/* 搜索字典树中是否存在该字符串 */
    	bool search(string word) {
            Trie* node = this->seachprefix(word);
            return node!=nullpter&&node->isEnd;
        }
    
    	/* 搜索字典树中是否有匹配前缀的字符串 */
    	bool startsWith(string prefix) {
            return this->searchprefix(prefix)!=nullptr;
        }
}

应用:

  • 前缀匹配
  • 词频统计
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值