字符串之字典树(Tries)

一颗根节点为空的树,从根节点的某一子节点出发到任意叶子结点的路径即为一个字符串。
代码比较多,但是很容易理解。
查找的效率会很高。

#define Max 26
typedef struct node  //结点的结构
{
    struct node *next[Max];  //每个节点最多26个孩子结点
    int num; //已存储孩子节点的个数
}Node;
Node *createNew()//创建一个新节点
{
    Node *p=new Node;
    for(int i=0;i<Max;i++)
        p->next[i]=NULL;
    p->num=0;
    return p;
}
void Insert_str(char str[],Node *head)//插入一个字符串
{
    int len=strlen(str);
    Node *t,*p=head;
    for(int i=0;i<len;i++)
    {
        int c=str[i]-'a';
        if(p->next[c]==NULL)
        {
            t=createNew();
            p->next[c]=t;
            p->num++;
             p=p->next[c];
        }
        else          p=p->next[c];
    }
}
int Search_str(char str[],Node *head)
{
    Node *p=head;
    int len=strlen(str);
    int count=0;
    for(int i=0;i<len;i++)
    {
        int c=str[i]-'a';
        if(p->next[c]==NULL)  return 0;
        else
        {
            p=p->next[c];
            count=p->num;
        }
    }
    return count;
}
int main()
{
    Node *head=createNew();
    scanf("%s",s);
    Insert_str(s,head);
    int c=Search_str(s);
    return 0;
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容