字典树
来源:互联网 发布:nginx 压力测试 编辑:程序博客网 时间:2024/06/07 09:17
字典树,是一种存取字符串的树状存储结构,以字符串的每一个字符为结点,不断扩展。从根节点到叶子结点,途中经过的结点的值连接起来就是该字符串。该存储方式可以有效的减少空间的浪费,有很多字符串可以公用一些结点,减少了空间上的开支。在查找的时候也比较方便,若查询到某一个字符时,该结点不存在,那么该字符串必然不存在。
#include <iostream>#include <cstring>#include <cstdlib>#include <cstdio>#include <cmath>using namespace std;#define maxn 26//结点定义typedef struct Trie{ int cnt; struct Trie* next[maxn];}Trie;Trie *root;//初始化void init(){ root = new Trie; root->cnt = 0; for(int i=0; i<26; i++) root->next[i] = NULL;}//插入单词void Insert_Tree(char *s){ int len = strlen(s); Trie *p = root,*q; for(int i=0; i<len; i++) { int num = s[i] - 'a'; if(!p->next[num]) { q = new Trie; q->cnt = 0; for(int j=0; j<26; j++) q->next[j] = NULL; p->next[num] = q; } p = p->next[num]; } p->cnt++;}//单词查找int Find_Tree(char *s){ int len = strlen(s); Trie *p = root; for(int i=0; i<len; i++) { int num = s[i] - 'a'; if(! p->next[num]) return 0; p = p->next[num]; } return p->cnt;}//销毁处理void Free_Tree(Trie *t){ if(!t) return ; for(int i=0; i<26; i++) Free_Tree(t->next[i]); delete t;}int main(){ init(); int n; scanf("%d",&n); char str[10]; while(n--) { scanf("%s",str); Insert_Tree(str); } int m; scanf("%d",&m); while(m--) { scanf("%s",str); if(Find_Tree(str)) printf("Find\n"); else printf("Not Find\n"); } Free_Tree(root);}
0 0
- 字典树
- 字典树
- 字典树
- 字典树
- 字典树
- 字典树。。
- 字典树
- 字典树
- 字典树
- 字典树
- 字典树
- 字典树
- 字典树
- 字典树
- 字典树
- 字典树
- 字典树
- 字典树
- hiho拓扑排序专题 ——第四十八、四十七周
- Shell编程基础(3)
- android亮屏、黑屏、解锁事件的系统广播接收
- 挺不错的移动端调试工具----debuggap
- Customised collectionView
- 字典树
- Haskell之Yesod开发–简单网站开发(四)
- JAVA 调用MQ
- [image processing]matlab
- iOS开发应用程序图标大小汇总
- sql两个表结果计算后合并数据
- 由于undo tablespace没有空间不够导致的问题
- Android_多媒体详解
- 并查集