http://acm.hdu.edu.cn/showproblem.php?pid=1251&&字典树

字典树水题,求公共前缀的个数。。。

#include<iostream>
#include<string.h>
#include<string>
#include<stdlib.h>
using namespace std;
typedef struct Tire
{
	int count;
	 struct Tire *next[26];

}*Node,T;
Node a;
void init()
{
	a=(Node)malloc(sizeof(T));
	for(int i=0;i<26;++i)
		a->next[i]=NULL;
}
void insert(string s)
{  
	Node head=a;
	int n=s.size();
	for(int i=0;i<n;++i)
	{
		int k=(int)(s[i]-97);
		if(head->next[k]==NULL)
		{
			head->next[k]=new T;
			head=head->next[k];
			head->count=1;
			for(int i=0;i<26;++i)
				head->next[i]=NULL;
		}
		else   { 
		         head=head->next[k];
				 head->count++;
		       }
	}
}
int find(string s)
{
	int n=s.size();
	Node head=a;
	for(int i=0;i<n;++i)
	{
		int  k=(int)(s[i]-97);
		if(head->next[k])   head=head->next[k];
		else  return 0;
	}
	return head->count;
}
int main()
{
	 char ch[10];
	 init();
	while(gets(ch),strcmp(ch,""))
			insert(ch);
	while(gets(ch))
		cout<<find(ch)<<endl;
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值