赞
踩
以下来源于百度百科:
在计算机科学中,Trie,又称字典树、单词查找树或键树,是一种树形结构,是一种哈希树的变种。典型应用是用于统计,排序和保存大量的字符串(但不仅限于字符串)。
特点:利用字符串的公共前缀来减少查询时间,最大限度地减少无谓的字符串比较,查询效率比哈希树高。
核心思想:空间换时间,利用字符串的公共前缀来降低查询时间的开销以达到提高效率。
例如:如给出字符串"abc","ab","bd","dda",根据该字符串序列构建一棵Trie树。则构建的树如下:
红色表示一个单词的结束。
Tire的三个基本性质:
1.根节点不包含字符,除根节点外每一个节点都只包含一个字符。
2.从根节点到某一节点,路径上经过的字符连接起来,为该节点对应的字符串。
3.每个节点的所有子节点包含的字符都不相同。
Tire树的实现:
数组:
- const int N = 1e5+10;
- int son[N][26], cnt[N], idx; // son存储Trie cnt存储每个节点的单词数,idx为节点编号
-
- // 插入
- void insert(string str)
- {
- int p = 0;
- for(int i=0; str[i]; i++)
- {
- int u = str[i] - 'a';
- if(!son[p][u]) son[p][u] = ++idx;
- p = son[p][u];
- }
- cnt[p]++;
- }
-
- // 查询
- int query(string str)
- {
- int p = 0;
- for(int i=0; str[i]; i++)
- {
- int u = str[i] - 'a';
- if(!son[p][u]) return 0;
- p = son[p][u];
- }
- return cnt[p];
- }
-

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

插入:
- Void InsertTire(Tire root,char* word)
- {
- Tire node=root;
- char *p=word;
- while(*p){
- if(node->nexe[*p-'a']==NULL)
- {
- node->next[*p-'a']=createTirenode();
- }
- node=node->next;
- p++;
- node->count+=1;
- }
- node->exist = true;
- }
查找:
- int TireSearch(Trie root,char*word)
- {
- Tire node = root;
- char *p = word;
- int id;
- while(*p)
- {
- id=*p-'a';
- node=node->next[id];
- ++p;
- if(node==NULL)
- return 0;
- }
- return node->count;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。