功能
字典樹是用數(shù)組存儲大量字符串的一種算法
字典樹算法開辟空間非常大,但是對于字符串插入和查詢有很快的速度
用法
結構
{
當前結點數(shù);
存儲字符串的數(shù)組[MAX_N][26];
存儲字符串結點數(shù)組[MAX_N];
}
例如存儲apple和apl的例子
下面一段代碼:
struct trietree
{
int nodenumber;? //結點數(shù)量
int *ch[MAX_N];? //存儲字符串數(shù)組指針 同int ch[MAX_N][26]
int node[MAX_N];//存儲字符串終止結點的數(shù)組
void init()//初始化函數(shù)
{
nodenumber=0;//結點數(shù)置0
memset(ch,0,sizeof(ch));
memset(node,0,sizeof(node));
}
void insert(char *str)//插入函數(shù)
{
int p=0;
for(int i=0;str[i];i++)
{
if(ch[p]==NULL)
{
ch[p]=new int[MAX_C];//開辟存儲空間
memset(ch[p],-1,sizeof(int)*MAX_C);
}
if(ch[p][str[i]-'a']==-1)
{
ch[p][str[i]-'a']=++nodenumber;
}
p=ch[p][str[i]-'a'];
}
node[p]++;//生成結點
}
};