字典树trie

版权声明:本文为博主原创文章,点个赞随便转 https://blog.csdn.net/qq_20200047/article/details/78993440
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstdlib>
#include<cstring>
#include<string>
#include<algorithm>
using namespace std;
#define inf 99999
int trie[5000][27],tol,tot;
char str[2000][27];
void inserted()
{
    tot=1;
    int t,i,len,root,id;
    for(t=0; t<tol; t++)
    {
        len=strlen(str[t]);
        root=0;
        for(i=0; i<len; i++) //if(str[t][i]>='a'&&str[t][i]<='z')
            id=str[t][i]-'a';//else id=str[t][i]-'A';
        if(!trie[root][id])
            trie[root][id]=++tot;
        root=trie[root][id];//顺着树往下找
    }
}
bool found()
{
    len=strlen(s);
    root=0;//从根结点开始找
    for(int i=0;s[i];i++)
    {
        int x=s[i]-'a';//
        if(trie[root][x]==0)   return false;//以root为头结点的x字母不存在,返回0
        root=trie[root][x];//为查询下个字母做准备,往下走
    }
    return true;//找到了
}
int main()
{
    int i,j,k;
    char c;
    i=0,j=0;
    while(scanf("%c",&c)!=EOF)
    {
        if((c>='a'&&c<='z')||(c>='A'&&c<='Z'))
        {
            str[i][j++]=c;
        }
        else if(c!='\n')
        {
            str[i++][j]='\0';
        }
    }
    tol=i;
    memset(trie,0,sizeof(trie));
    inserted();


    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_20200047/article/details/78993440