标签:单词查找
友情题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1247
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int N=30;
const int MAX=50005;
char word[MAX][30];
struct node
{
bool temp;
node *next[N];
node()
{
temp=false;
memset(next,0,sizeof(next));
//next是表示每层有多少种类的数,如果只是小写字母,则26即可,
//若改为大小写字母,则是52,若再加上数字,则是62了
}
};
void insert(node *rt,char *s)
{
int i,t;
i=0;
node *p=rt;
while(s[i])
{
t=s[i++]-'a';
if(p->next[t]==NULL)
p->next[t]=new node();
p=p->next[t];
}
p->temp=true;//指向单词尾部
}
bool search(node *rt,char s[])
{
int i,top;
i=top=0;
int stack[MAX];
node *p=rt;
while(s[i])
{
int t=s[i++]-'a';
if(p->next[t]==NULL)
return false;
p=p->next[t];
if(p->temp&&s[i]) //找到含有子单词的分割点 并且该字符还没结束
stack[top++]=i; //将这个分割点入栈 ,然后循环判断剩下的部分是否含有一个子单词
}
while(top) //从这些分割点开始找
{
bool ok=true; //标记是否找到
i=stack[--top]; //第一个分割点
p=rt;
while(s[i])
{
int t=s[i++]-'a';
if(p->next[t]==NULL)
{
ok=false; //没有找到
break;
}
p=p->next[t];
}
if(ok&&p->temp)
return true;
}
return false;
}
int main()
{
int i=0;
node *rt=new node();
while(gets(word[i]))
{
insert(rt,word[i]);
i++;
}
for(int j=0;j<i;j++)
{
if(search(rt,word[j]))
{
cout<<word[j]<<endl;
}
}
return 0;
}标签:单词查找
原文地址:http://blog.csdn.net/holyang_1013197377/article/details/45102055