Trie树
来源:互联网 发布:sql update 指定行 编辑:程序博客网 时间:2024/05/29 11:58
字典树用于单词统计,查询,非常有用。现在就Trie树给出C语言实现。
#include <stdio.h>#include <malloc.h>#define MAXN 26struct Trie{ int count; //单词计数 int flag; // 1表示是单词,0表示不是单词 struct Trie *next[MAXN];};struct Trie *rt;//初始化Trie树void trie_init(){ int i; rt = (struct Trie*)malloc(sizeof(struct Trie)); rt->count = 0; rt->flag = 0; for(i=0; i<MAXN; ++i) rt->next[i] = NULL;}//插入单词void trie_insert(char *s){ int i; struct Trie *tmp = rt; for(s; *s!='\0'; ++s){ if(tmp->next[*s -'a'] == NULL){ struct Trie *cur = (struct Trie*)malloc(sizeof(struct Trie)); cur->count = 0; cur->flag = 0; for(i=0; i<MAXN; ++i) cur->next[i] = NULL; tmp->next[*s -'a'] = cur; } tmp->count++; tmp = tmp->next[*s -'a']; } tmp->flag = 1; tmp->count++;}//查询给定字符串前缀的单词数目int trie_search(char *s){ struct Trie *tmp = rt; for(s; *s!='\0'; ++s){ if(tmp->next[*s -'a'] == NULL) return 0; tmp = tmp->next[*s -'a']; } return tmp->count;}//删除整个Trie树void trie_del(struct Trie *root){ int i; for(i=0; i<MAXN; ++i){ if(root->next[i] != NULL) trie_del(root->next[i]); } free(root);}int main(){ int i, n, m; char ch[15]; FILE *fin; fin = fopen("input.txt", "r"); while(fscanf(fin, "%d", &n) != EOF){ trie_init(); for(i=0; i<n; ++i){ fscanf(fin, "%s", ch); trie_insert(ch); } fscanf(fin, "%d", &m); for(i=0; i<m; ++i){ fscanf(fin, "%s", ch); printf("%d\n", trie_search(ch)); } trie_del(rt); } return 0;}
0 0
- hihoCoder1014 Trie树 [Trie]
- TRIE树
- TRIE树
- TRIE树
- trie 树
- Trie树
- Trie树
- Trie树
- Trie树
- trie树
- trie树
- Trie 树
- Trie树
- Trie 树
- trie 树
- Trie树
- Trie树
- Trie树
- java引用webRoot下的文件
- 【Hibernate】——悲观锁和乐观锁
- Java日期转换SimpleDateFormat格式大全
- Dubbo-redis集群搭建
- 解决Maven 默认jre1.5
- Trie树
- Java小程序:字符串中,统计每个字符出现的次数
- springmvc +hibernate+ spring+ maven框架搭建
- ecshop二次开始--头像上传
- Swing的线程机制
- 卸载程序,清除目录文件
- php 利用远程jpg图片创建新jpg图片
- 使用上下文菜单ContextMenu
- LTE与VOLTE基础知识(2)