当前位置:   article > 正文

数据结构4:Tire树入门_tirenode

tirenode

以下来源于百度百科:

在计算机科学中,Trie,又称字典树、单词查找树或键树,是一种树形结构,是一种哈希树的变种。典型应用是用于统计,排序和保存大量的字符串(但不仅限于字符串)。

特点:利用字符串的公共前缀来减少查询时间,最大限度地减少无谓的字符串比较,查询效率比哈希树高。

核心思想:空间换时间,利用字符串的公共前缀来降低查询时间的开销以达到提高效率。

例如:如给出字符串"abc","ab","bd","dda",根据该字符串序列构建一棵Trie树。则构建的树如下:
 

红色表示一个单词的结束。

Tire的三个基本性质:

1.根节点不包含字符,除根节点外每一个节点都只包含一个字符。

2.从根节点到某一节点,路径上经过的字符连接起来,为该节点对应的字符串。

3.每个节点的所有子节点包含的字符都不相同。

Tire树的实现:

数组: 

  1. const int N = 1e5+10;
  2. int son[N][26], cnt[N], idx; // son存储Trie cnt存储每个节点的单词数,idx为节点编号
  3. // 插入
  4. void insert(string str)
  5. {
  6. int p = 0;
  7. for(int i=0; str[i]; i++)
  8. {
  9. int u = str[i] - 'a';
  10. if(!son[p][u]) son[p][u] = ++idx;
  11. p = son[p][u];
  12. }
  13. cnt[p]++;
  14. }
  15. // 查询
  16. int query(string str)
  17. {
  18. int p = 0;
  19. for(int i=0; str[i]; i++)
  20. {
  21. int u = str[i] - 'a';
  22. if(!son[p][u]) return 0;
  23. p = son[p][u];
  24. }
  25. return cnt[p];
  26. }

 

 

结构体:

  1. typedef struct TireNode{
  2. int count; // 统计单词前缀出现的次数
  3. struct TireNode *next[26]; // 用0~25 来表示a~z,存入时 相应的字符减一个'a'就行了。
  4. bool exist; // 记录是不是构成一个单词
  5. }TireNode,*Tire;
  6. TireNode* CreatTireNode()
  7. {
  8. Tire node = new Tirenode; //动态分配空间
  9. node->count=0;
  10. memset(node->next,0,sizeof(node->next));
  11. return node;
  12. }
  13. int main()
  14. {
  15. tire root=CreatTireNode();
  16. }

插入:

  1. Void InsertTire(Tire root,char* word)
  2. {
  3. Tire node=root;
  4. char *p=word;
  5. while(*p){
  6. if(node->nexe[*p-'a']==NULL)
  7. {
  8. node->next[*p-'a']=createTirenode();
  9. }
  10. node=node->next;
  11. p++;
  12. node->count+=1;
  13. }
  14. node->exist = true;
  15. }

查找:

  1. int TireSearch(Trie root,char*word)
  2. {
  3. Tire node = root;
  4. char *p = word;
  5. int id;
  6. while(*p)
  7. {
  8. id=*p-'a';
  9. node=node->next[id];
  10. ++p;
  11. if(node==NULL)
  12. return 0;
  13. }
  14. return node->count;
  15. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/727786
推荐阅读
相关标签
  

闽ICP备14008679号