标签:字典 style strong 存在 节点 struct div 查找树 aik
1.概念
1.又称单词查找树,Trie树,是一种树形结构,是一种哈希树的变种。典型应用是用于统计,排序和保存大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。
2.优点:
利用字符串的公共前缀来减少查询时间,最大限度地减少无谓的字符串比较,查询效率比哈希树高。
1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<string.h> 4 5 typedef struct node 6 { 7 int nFlag; 8 struct node *pCharacter[26]; 9 char *str;//若某节点是某个单词的结尾,则把该单词保存在该节点中。 10 }TrieTree; 11 12 void AddWord(TrieTree *pTree,char *str) 13 { 14 int i; 15 TrieTree *pTemp = NULL; 16 for(i = 0;i<strlen(str);i++) 17 { 18 //节点的对应位置空 添加节点 19 if(pTree->pCharacter[str[i]-97] == NULL) 20 { 21 pTemp = (TrieTree*)malloc(sizeof(TrieTree)); 22 memset(pTemp,0,sizeof(TrieTree)); 23 24 pTree->pCharacter[str[i]-97] = pTemp; 25 } 26 27 //向下走 28 pTree = pTree->pCharacter[str[i]-97]; 29 } 30 31 //末尾标记 32 pTree->nFlag++; 33 pTree->str = str; 34 } 35 36 37 TrieTree *CreateTrieTree(char *str[],int nLength) 38 { 39 if(str == NULL || nLength <=0)return NULL; 40 41 TrieTree *pRoot = NULL; 42 pRoot = (TrieTree*)malloc(sizeof(TrieTree)); 43 memset(pRoot,0,sizeof(TrieTree)); 44 45 //将字符串依次添加 46 int i; 47 for(i = 0;i<nLength;i++) 48 { 49 AddWord(pRoot,str[i]); 50 } 51 return pRoot; 52 } 53 54 void Search(TrieTree *pRoot,char *str) 55 { 56 if(str == NULL || pRoot == NULL)return; 57 58 int i; 59 for(i = 0;i<strlen(str);i++) 60 { 61 if(pRoot->pCharacter[str[i]-97] == NULL) 62 { 63 printf("failed.\n"); 64 return; 65 } 66 pRoot = pRoot->pCharacter[str[i]-97]; 67 } 68 69 //检测末尾标志 70 if(pRoot->nFlag != 0 ) 71 { 72 printf("%s\n",pRoot->str); 73 return; 74 } 75 else 76 { 77 printf("hhhh failed.\n"); 78 return; 79 } 80 } 81 82 void Traversal(TrieTree *pTree) 83 { 84 if(pTree == NULL) 85 return; 86 87 if(pTree->nFlag != 0) 88 { 89 printf("%s\n",pTree->str); 90 } 91 92 int i; 93 for(i = 0;i<26;i++) 94 { 95 Traversal(pTree->pCharacter[i]); 96 } 97 } 98 99 int main() 100 { 101 char *str[] = {"app","apple","orange","lemon","logo","ball","tie","glory"}; 102 TrieTree *pRoot = CreateTrieTree(str,8); 103 Traversal(pRoot); 104 printf("----------------------\n"); 105 Search(pRoot,"ball"); 106 return 0; 107 }
)
标签:字典 style strong 存在 节点 struct div 查找树 aik
原文地址:http://www.cnblogs.com/curo0119/p/7953972.html