zoukankan      html  css  js  c++  java
  • 字典树

    字典树又叫trie树,利用字符串的公共前缀来降低查询时间的开销,以及字符串的存储开销。所以经常被搜索引擎系统用于文本词频统计。

    字典树的数据结构

    #define MAX  26
    typedef struct Tree
    {
        int count;         //用来标记该节点是个可以形成一个单词,如果count!=0,则从根节点到该节点的路径可以形成一个单词
        struct Tree *child[MAX];
    }Node,*Trie_node;

    字典树的生成

    Node* CreateTrie()                             //创建trie节点树
    {
        Node *node=(Node*)malloc(sizeof(Node));
        memset(node,0,sizeof(Node));
        return node;
    }
    void insert(Trie_node root,char *str)      //trie树插入结点
    {
        Node *t=root;
        int len=strlen(str);
       for(int i=0;i<len;i++)
        {
         if(t->child[str[i]-'a']==NULL)
            {
             Node *tmp=(Node*)malloc(sizeof(Node));
               memset(tmp,0,sizeof(Node));
             t->child[str[i]-'a']=tmp;
            }
         t=t->child[str[i]-'a'];
    
        }
        t->count++;
    }

    查找该单词是否在字典树中

    void search_str(Trie_node root,char *str)             //查找串是否在该trie树中
    {
        Node *t=root;
         int len=strlen(str);
       for(int i=0;i<len;i++)
        {
         if(t->child[str[i]-'a']!=NULL)
            {
             t=t->child[str[i]-'a'];
    
            }
         else
                 break;
        }
        if(str[len]=='')
        {
         if(t->count!=0)
                cout<<"该字符串在该trie树中
    ";
        }
        else
            cout<<"该字符串不在trie树中
    ";
    }

    释放空间

    void del(Trie_node root)      //释放整个字典树占的堆空间
    {
        int i;
        for(i=0;i<MAX;i++)
        {
         if(root->child[i]!=NULL)
                del(root->child[i]);
        }
        free(root);
    }
  • 相关阅读:
    linux设置定时任务的方法(自己总结)
    SecureCRT上传和下载文件
    ajax上传文件类型
    分页业务逻辑
    $.load
    数组中多条对象去重方式
    jquery cookie
    鼠标滚轮事件(浏览器兼容性写法)
    用cookie保存用户的登录信息,规定保存的期限
    获取url参数值
  • 原文地址:https://www.cnblogs.com/wintersong/p/5170109.html
Copyright © 2011-2022 走看看