字典树 模板
/*******************************************************************************【字典樹】此模板主要是針對都是小寫字母的。其他情況在此基礎(chǔ)上改一改就可以了,要懂得靈活運(yùn)用。 ********************************************************************************/struct trie /*字典樹的節(jié)點(diǎn)內(nèi)容*/
{int count;/*計(jì)算該節(jié)點(diǎn)出現(xiàn)的次數(shù)*/trie *next[26];/*一個(gè)節(jié)點(diǎn)有26個(gè)指針(孩子),即'a'-'z'*/
};trie *root;trie* newtrie()/*建立一個(gè)節(jié)點(diǎn)。(也可以用建立個(gè)大的數(shù)組,指針指向數(shù)組不同位置)*/
{ trie *t; t=(trie*)malloc(sizeof(struct trie)); memset(t,0,sizeof(struct trie)); return t;
}void Insert(char *ch) /*插入函數(shù),將該字符串插入到字典樹中 */
{ int i; trie *t,*s; s=root; for(i=0;ch[i];i++) { if(s->next[ch[i]-'a']) { s=s->next[ch[i]-'a']; s->count=s->count+1; } else { t=newtrie(); s->next[ch[i]-'a']=t; s=t; s->count=1; } }
} int Search(char *ch)/*搜索函數(shù),返回0則代表字典樹不存在該字符串,反之亦然 */
{ int i; trie *s=root; if(ch[0]==0) return 0; for(i=0;ch[i];i++) { if(s->next[ch[i]-'a']) s=s->next[ch[i]-'a']; else break; } if(ch[i]==0) return s->count; else return 0;
} void Delete(char *ch)/*刪除函數(shù),將該字符串從字典樹中刪除(刪除之前記得事先判斷存不存在該字符串)*/
{ int i; trie *s; s=root; for(i=0;ch[i];i++) { s=s->next[ch[i]-'a'];s->count=s->count-1;}
}
總結(jié)
- 上一篇: 后缀数组 模板
- 下一篇: 二分匹配(匈牙利算法)模板