trie树

http://blog.csdn.net/terro/article/details/1745699

Trie数:思想表示词典数,即用树形结构表示词典。

仅需要修改TrieNode中参数即可。

1)可以用来查找相同前缀,最长的前缀

2)查找相同前缀的个数

3)查找某个单词是否出现过

  1. #include <iostream>
  2. using namespace std;
  3. #include <stdio.h>
  4. #include <string.h>
  5. #define MAX 26
  6. typedef struct TrieNode {
  7. int nCount;
  8. struct TrieNode *next[MAX];
  9. }TrieNode;
  10. TrieNode Memory[1000000];  //保存内容和trie先序遍历结果一致,创建树按照先序创建。
  11. int alloc = 0;
  12. void initTrieRoot(TrieNode **pRoot) {
  13. *pRoot = NULL;
  14. }
  15. TrieNode *createTrieNode(){
  16. int i;
  17. TrieNode *p=NULL;
  18. p=&Memory[alloc++];
  19. p->nCount = 1;
  20. for(i=0;i<MAX;i++) {
  21. p->next[i] = NULL;
  22. }
  23. return p;
  24. }
  25. void insertTrie(TrieNode *pRoot,char *s) {
  26. int i,k;
  27. if(pRoot==NULL || *s=='\0') {
  28. return ;
  29. }
  30. TrieNode *p=pRoot;
  31. i = 0;
  32. while(s[i]!='\0'){
  33. k=s[i++]-'a';
  34. if(p->next[k]!=NULL){
  35. p->next[k]->nCount++;
  36. } else {
  37. p->next[k] = createTrieNode();
  38. }
  39. p=p->next[k];
  40. }
  41. }
  42. int searchTrie(TrieNode * pRoot,char *s) {
  43. TrieNode *p;
  44. int i,k;
  45. if(pRoot==NULL){
  46. return 0;
  47. }
  48. p = pRoot;
  49. i=0;
  50. while(s[i]){
  51. k=s[i++]-'a';
  52. if(p->next[k]==NULL) return 0;
  53. p = p->next[k];
  54. }
  55. return p->nCount;
  56. }
  57. int main(){
  58. memset(Memory,0,sizeof(Memory));//初始化数空间
  59. TrieNode *root=createTrieNode(); //根节点
  60. int n;
  61. cin>>n;
  62. char input[32];
  63. for(int i=0;i<n;i++) {
  64. cin>>input;
  65. insertTrie(root,input);
  66. }
  67. // TrieNode *tmp = root;  //遍历输出,要控制输出条件,避免进入死循环,用不变量模式进行控制。
  68. // while(tmp!=NULL) {
  69. // int j=0;
  70. // for(j=0;j<MAX;j++) {
  71. // if(tmp->next[j]!=NULL) {
  72. // cout<<j<<"\t";
  73. // break;
  74. // }
  75. // }
  76. // if(j<MAX) tmp = tmp->next[j];  //如果不填加判断条件,则进入空指针,如j  > MAX . 
  77. // else break;
  78. // }
  79. // cout<<endl;
  80. // }
  81. // char find[] = {'b','a','a','b','b'};
  82. // char *find = "babb";
  83. char find[11];
  84. int m;
  85. cin>>m;
  86. int i=0;
  87. while(i<m) {
  88. cin>>find;
  89. cout<<searchTrie(root,find)<<endl;
  90. i++;
  91. }
  92. // for(int i=0;i<alloc;i++) {
  93. // cout<<Memory[i].nCount<<"\t";
  94. // }
  95. cout<<endl;
  96. return 0;
  97. }
posted @ 2014-07-20 11:37  purejade  阅读(172)  评论(0编辑  收藏  举报