trietree的一个小练习
生活随笔
收集整理的這篇文章主要介紹了
trietree的一个小练习
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
trietree又稱為字典樹。顧名思義,它是一種用來快速查找字符串的樹形數據結構。
借用下網上的圖哈~trietree結構如下:
實現方式大多為數組實現。我覺得這里需要注意的有這么幾點:
1.當一個字符串很長時,必然導致該樹的一個分支特別長。因此該數據結構不太適合用于字符串長度過長的情況。
2.因為是數組存儲兄弟節點,因此必須根據字符的情況定義一個合適的數組大小(通常為128),以達到節省空間的目的。
3.可以用到的情況有:統計字符串出現個數,統計單詞的前綴,字符串的排序等。
以下為其實現的一個小例子:
#include<stdio.h> #include<stdlib.h> #include<string.h> #define MAXNUM 130 typedef struct tnode{int _count; struct tnode *next[MAXNUM]; //slibing nodes }t_node; int insert(const char* str,t_node *node){char *pos=str; // int i;t_node *nextnode,*curnode=node; if(*pos==0) return 0;for(;*pos;pos++){ //util the end of the stringif(curnode->next[*pos]==NULL){ //if not exitscurnode->next[*pos]=(t_node *)malloc(sizeof(t_node));memset(curnode->next[*pos],0,sizeof(t_node));}nextnode=curnode->next[*pos]; //change the nodecurnode=nextnode;} curnode->_count++;printf("str is :%s total:%d \n",str,curnode->_count);return 0; } void destory(t_node *node){int i; for(i=0;i<MAXNUM;i++){if(node->next[i]){destory(node->next[i]);free(node->next[i]); //recursion}} } int main(void){t_node root;char buffer[MAXNUM];memset(&root,0,sizeof(t_node));while(fgets(buffer,MAXNUM,stdin)!=NULL){buffer[strlen(buffer)-1]=0;printf("begin to handle %s\n",buffer);insert(buffer,&root);}destory(&root);return 0; }轉載于:https://www.cnblogs.com/aLittleBitCool/archive/2011/08/22/2148854.html
總結
以上是生活随笔為你收集整理的trietree的一个小练习的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Shell 参数传递、 $* 与 $@
- 下一篇: Hibernate4 注解方法说明