字典树
多个字符串进行反复查找
单词查找
单词计数
单词排序
核心思想
创建字典树,之后进行查找,一定非空树,节点中无字符,以下边结点代表上面节点的下标,一种单词中字符共用的思想
代码
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct sNode
{
int nCount;
struct sNode ** arrchar;
}TireTree;
TireTree * addNode()
{
TireTree * pNode = (TireTree *)malloc(sizeof(TireTree));
pNode->nCount = 0;
pNode->arrchar = (TireTree **)malloc(sizeof(TireTree *) * 26);
int i;
for(i = 0; i < 26 ; i ++ )
{
pNode->arrchar[i] = NULL;
}
return pNode;
}
void addWorld(TireTree ** pRoot,char * str)
{
if(*pRoot == NULL || pRoot == NULL)return;
int len = strlen(str);
int i = 0 ;
TireTree * pMark = (*pRoot);
while(i < len)
{
if(pMark->arrchar[str[i] - 97] == NULL)
{
pMark->arrchar[str[i] - 97] = addNode();
}
pMark = pMark->arrchar[str[i] - 97];
i ++;
}
pMark->nCount ++;
}
void CreateTree(TireTree ** pRoot,char ** arrWorld,int length)
{
//初始化根结点
*pRoot = addNode();
int i;
for(i = 0 ; i < length ; i ++)
{
addWorld(pRoot,arrWorld[i]);
}
}
int SearchWorld(TireTree * pRoot,char * str)
{
if(pRoot == NULL)
{
return -1;
}
int i = 0;
while(i < strlen(str))
{
if(pRoot->arrchar[str[i] - 97] == NULL)
{
return -1;
}
pRoot = pRoot->arrchar[str[i] - 97];
i ++;
}
if(pRoot->nCount > 0)
{
return pRoot->nCount;
}
else
{
return -1;
}
}