zoukankan      html  css  js  c++  java
  • Trie

    #include <iostream>
    #include<cstdlib>
    #define MAX 26
    using namespace std;
     
    typedef struct TrieNode                     //Trie结点声明 
    {
        bool isStr;                            //标记该结点处是否构成单词 
        struct TrieNode *next[MAX];            //儿子分支 
    }Trie;
     
    void insert(Trie *root,const char *s)     //将单词s插入到字典树中 
    {
        if(root==NULL||*s=='')
            return;
        int i;
        Trie *p=root;
        while(*s!='')
        {
            if(p->next[*s-'a']==NULL)        //如果不存在,则建立结点 
            {
                Trie *temp=(Trie *)malloc(sizeof(Trie));
                for(i=0;i<MAX;i++)
                {
                    temp->next[i]=NULL;
                }
                temp->isStr=false;
                p->next[*s-'a']=temp;
                p=p->next[*s-'a'];   
            }   
            else
            {
                p=p->next[*s-'a'];
            }
            s++;
        }
        p->isStr=true;                       //单词结束的地方标记此处可以构成一个单词 
    }
     
    int search(Trie *root,const char *s)  //查找某个单词是否已经存在 
    {
        Trie *p=root;
        while(p!=NULL&&*s!='')
        {
            p=p->next[*s-'a'];
            s++;
        }
        return (p!=NULL&&p->isStr==true);      //在单词结束处的标记为true时,单词才存在 
    }
     
    void del(Trie *root)                      //释放整个字典树占的堆区空间 
    {
        int i;
        for(i=0;i<MAX;i++)
        {
            if(root->next[i]!=NULL)
            {
                del(root->next[i]);
            }
        }
        free(root);
    }
    

      

  • 相关阅读:
    变色龙
    生在北极圈内的“瑞典之声”Sofia Jannok
    “清一色”数列1,11,111,1111,...
    1100 10100 PAGE ERROR
    The Lazarus Project
    数字“黑洞”495
    don't you forget the EXIF~!
    行和列
    小谈奇数平方与偶数平方
    “码农”的得力工具math
  • 原文地址:https://www.cnblogs.com/TheRoadToAu/p/8053637.html
Copyright © 2011-2022 走看看