您的位置:首页 > 其它

字典树:求以某字符串开始的单词个数

2015-09-14 23:51 369 查看
http://hihocoder.com/contest/hiho2/problem/1

与之前做的有点像:http://blog.csdn.net/u011644423/article/details/37833905

稍微改下,注意每次在建立Trie树时同时进行统计

#include <stdio.h>
#include<stdlib.h>
#define MAX 26
//using namespace std;
typedef struct TrieNode                     //Trie结点声明
{
//bool isStr;
int count;
//标记该结点处是否构成单词 可能大于一
struct TrieNode *next[MAX];            //儿子分支
}Trie;

void insert(Trie *root,const char *s)     //将单词s插入到字典树中
{
if(root==NULL||*s=='\0')
return;
int i;
Trie *p=root;
while(*s!='\0')
{
if(p->next[*s-'a']==NULL)        //如果不存在,则建立结点
{
Trie *temp=(Trie *)malloc(sizeof(Trie));
for(i=0;i<MAX;i++)
{
temp->next[i]=NULL;

}
// temp->isStr=false;
p->next[*s-'a']=temp;
p=p->next[*s-'a'];
p->count=1;
}
else
{
p=p->next[*s-'a'];
(p->count)++;
}
s++;
}
// p->isStr=true;                       //单词结束的地方标记此处可以构成一个单词
}

int findmin(Trie *root,char *str){
Trie *p=root;
int num=0;
while(*str!='\0'){
if(p->next[*str-'a']==NULL){
num=0; break;
}

num=(p->next[*str-'a'])->count;
//    printf("%c",*str);
p=p->next[*str-'a'];
str++;

}
return num;
}
void del(Trie *root)                      //释放整个字典树占的堆区空间
{                                           //递归
int i;
for(i=0;i<MAX;i++)
{
if(root->next[i]!=NULL)
{
del(root->next[i]);
}
}
free(root);
}

int main(int argc, char *argv[])
{
int i,j;
//  int n,m;                              //n为建立Trie树输入的单词数,m为要查找的单词数

Trie *root= (Trie *)malloc(sizeof(Trie));
for(i=0;i<MAX;i++)
{
root->next[i]=NULL;
}
//root->isStr=false;
//scanf("%d",&n);
//getchar();

int n;
scanf("%d",&n);
for(j=1;j<=n;j++){
getchar();
char s[12];
scanf("%s",s);
insert(root,s);
}
//    while(scanf("%s",s[gsum])!=EOF)
//        //scanf("%s",s);
//    {
//
//        insert(root,s[gsum]);
//        getchar();
//        gsum++;
//    }
int m;
scanf("%d",&m);

for(j=1;j<=m;j++){
getchar();
char s2[12];
scanf("%s",s2);
printf("%d\n",findmin(root,s2));
}

// del(root);                         //释放空间很重要
return 0;
}


随便说下。 用博客园写博客比csdn爽太多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: