数据结构 哈希表 字典树

来源:互联网 发布:兰州知豆电动车租赁 编辑:程序博客网 时间:2024/05/18 00:11

输入N个字符串

每个字符串大小小于10

输出出现次数最多的字符串和次数



#include <iostream>

#include <cstdio>
#include <string.h>
#include <malloc.h>
using namespace std;
struct Tire
{
   int count;//表示字符串出现的次数
   struct Tire *tire[26];//每个节点下面最多都还可以有26个节点
}*a;
void init()
{
a=(Tire*)malloc(sizeof(Tire));
for(int i=0;i<26;i++)
a->tire[i]=NULL;//初始化时,全部赋值为空
}
int insert(char ch[])
{
int length=strlen(ch);
Tire *head=a;
int i,j,k;
for(int i=0;i<length;++i)
{
k=(int)(ch[i]-97);
if(head->tire[k]==NULL)//如果为空,说明该字母没有出现过,则以该节点为父节点,
                         //再产生新的节点,且count值为0。
{
head->tire[k]=new Tire;
head=head->tire[k];
head->count=0;
for(j=0;j<26;++j)
head->tire[j]=NULL;//产生新节点后,还要对其进行赋值,即初始化。
}
   else
     head=head->tire[k];//如果存在的话,则指向下一个节点。
}
head->count++;//将该字符串保存在字典树中后,count值加1。
return head->count;
}
int main()
{
char s[10],ss[10];
init();//初始化字典树
int n;
scanf("%d",&n);
int max=0,sum=0;
while(n--)
{
scanf("%s",s);
sum=insert(s);//插入字符串,insert()函数的返回值即为当前此字符串出现的次数。
if(sum>max)
{
strcpy(ss,s);
max=sum;
}
    }
  printf("%s %d\n",ss,max);
//system("pause");
return 0;
}
0 1
原创粉丝点击