栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

字典树(前缀树)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

字典树(前缀树)

图片来源:百度百科

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

1.静态

#include
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>n>>m;
    while(n--)
    {
        cin>>str;
        insert();
    }
    while(m--)
    {
        cin>>str;
        cout< 

2.动态(来源:力扣)

class Trie {
private:
    vector 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;
    }
};

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/722303.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号