字典树(前缀树)

图片来源:百度百科

功能在o(n)的时间插入和查询字符串,n是字符串长度

1.静态

#include<iostream>
using namespace std;
const int N=1e6+10;
int son[N][26],cnt[N],idx;//cnt表示该字符串的数量,son表示字符串的某个字符的下一个节点的位置,其中字符串最后一个字符的son值表示该字符串的编号
int n,m;
string str;
void insert()//插入字符串
{
    int p=0;
    for(int i=0;i<str.size();i++)
    {
        if(!son[p][str[i]-'a']) son[p][str[i]-'a']=++idx;//如果在这个字典树中没有就建立一条连接下一个字符的边,并且给这个字符编号
        p=son[p][str[i]-'a'];
    }
    cnt[p]++;//记录字符串数量
}
int query()//返回前缀数量
{
    int p=0,res=0;
    for(int i=0;i<str.size();i++)
    {
        if(!son[p][str[i]-'a']) return res;//如果已经没有后面的字符了说明已经查询了所有的字典前缀可以直接返回
        p=son[p][str[i]-'a'];
        res+=cnt[p];
    }
    return res;
}
int main()
{
    cin>>n>>m;
    while(n--)
    {
        cin>>str;
        insert();
    }
    while(m--)
    {
        cin>>str;
        cout<<query()<<endl;
    }
    return 0;
}

2.动态(来源:力扣)

class Trie {
private:
    vector<Trie*> children;
    bool isEnd;

    Trie* searchPrefix(string prefix)
    {
        Trie* node=this;
        for(char ch:prefix)
        {
            ch-='a';
            if(node->children[ch]==nullptr)
                return nullptr;
            node=node->children[ch];
        }
        return node;
    }
public:
    Trie() :children(26),isEnd(false){}
    
    void insert(string word) {
        Trie *node=this;
        for(char ch:word)
        {
            ch-='a';
            if(node->children[ch]==nullptr)
                node->children[ch]=new Trie();
            node=node->children[ch];
        }
        node->isEnd=true;
    }
    
    bool search(string word) {
        Trie* node = this->searchPrefix(word);
        return node!=nullptr&&node->isEnd;
    }
    
    bool startsWith(string prefix) {
        return this->searchPrefix(prefix)!=nullptr;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值