码迷,mamicode.com
首页 > 其他好文 > 详细

字典树

时间:2018-09-01 12:15:52      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:str   gif   sea   color   ==   准备   分享图片   next   turn   

技术分享图片
int tot=1,n;
int trie[maxn][26];
bool isw[maxn]; //查询整个单词用
void insert(char *s,int rt)
{
    for(int i=0;s[i];i++)
    {
        int x=s[i]-a;
        if(trie[rt][x]==0)//现在插入的字母在之前同一节点处未出现过 
        {
            trie[rt][x]=++tot;//字母插入一个新的位置,否则不做处理 
        }
        rt=trie[rt][x];//为下个字母的插入做准备  
    }
    /*isw[rt]=true;标志该单词末位字母的尾结点,在查询整个单词时用到*/
}//插入查找
bool find(char *s,int rt)
{
    for(int i=0;s[i];i++)
    {
        int x=s[i]-a;
        if(trie[rt][x]==0)return false;//以rt为头结点的x字母不存在,返回0 
        rt=trie[rt][x];//为查询下个字母做准备 
    }
    return true;
    //查询整个单词时,应该return isw[rt] 
}//查找
int main()
{  
  int rt=1;
  insert(s,rt);  //插入
  find(s,rt);  //查找
}
数组-查找单词
技术分享图片
struct node
{
    node *next[28];
    bool is;
    node()
    {
        is=false;
        memset(next,0,sizeof(next));
    }
};
void insert(node *root,char s[])
{
    int i=0;
    node *p=root;
    while(s[i])
    {
        int j=s[i++]-a;
        if(p->next[j]==NULL) p->next[j]=new node();
        p=p->next[j];
    }
    p->is=true;
}
int search(node *root,char s[])
{
    i=0,len=0;
    node *p=root;
    while(s[i])
    {
        int j=s[i++]-a;
        if(p->next[j]==NULL) return 0;  //查不到
        p=p->next[j];
    }
    return 1;
}
指针-查找单词
技术分享图片
int trie[400001][26],len,root,tot,sum[400001];
bool p;
int n,m; 
char s[11];
void insert()
{
    len=strlen(s);
    root=0;
    for(int i=0;i<len;i++)
    {
        int id=s[i]-a;
        if(!trie[root][id]) trie[root][id]=++tot;
        sum[trie[root][id]]++;//前缀后移一个位置保存 
        root=trie[root][id];
    }
}
int search()
{
    root=0;
    len=strlen(s);
    for(int i=0;i<len;i++)
    {
        int id=s[i]-a;
        if(!trie[root][id]) return 0;
        root=trie[root][id];
    }//root经过此循环后变成前缀最后一个字母所在位置的后一个位置 
    return sum[root];//因为前缀后移了一个保存,所以此时的sum[root]就是要求的前缀出现的次数 
}
数组-前缀
技术分享图片
char s[11];
int n,m;
bool p;
struct node
{
    int count;
    node * next[26];
}*root;
node * build()
{
    node * k=new(node);
    k->count=0;
    memset(k->next,0,sizeof(k->next));
    return k;
}
void insert()
{
    node * r=root;
    char * word=s;
     while(*word)
    {
        int id=*word-a;
        if(r->next[id]==NULL) r->next[id]=build();
        r=r->next[id];
        r->count++;
        word++;
    }
}
int search()
{
    node * r=root;
    char * word=s;
    while(*word)
    {
        int id=*word-a;
        r=r->next[id];
        if(r==NULL) return 0;
        word++;
    }
    return r->count;
}
指针

 

字典树

标签:str   gif   sea   color   ==   准备   分享图片   next   turn   

原文地址:https://www.cnblogs.com/ww123/p/9569095.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!