Hat’s Words

A hat’s word is a word in the dictionary that is the concatenation of exactly two other words in the dictionary. 
You are to find all the hat’s words in a dictionary. 
Input
Standard input consists of a number of lowercase words, one per line, in alphabetical order. There will be no more than 50,000 words. 
Only one case. 
Output
Your output should contain all the hat’s words, one per line, in alphabetical order.
Sample Input
a
ahat
hat
hatword
hziee
word
Sample Output
ahat

hatword

题目意思:给你一些单词,看能否由其中的两个组成另外一个单词,能就输出这个单词。

解题思路:利用字典树,将这些单词进行建树,然后再将他们输入进去进行查找,找到一个单词后,记录

这个点,再将这个点之后的单词提取出来,输入查找,若找到,那么这个两个单词组成的单词

便存在。

#include<iostream>
#include<cstring>
#include<algorithm>

using namespace std;

char s[51000][110];

struct trie{
	int v;
	trie *next[26];
	trie(){
		for(int i=0;i<26;i++)
		{
			v=0;
			next[i]=NULL;
		}
	}
}; 

trie *root;
bool flag;

void creat(trie *root,char *str)
{
    int len=strlen(str);
	trie *p=root,*q;
	for(int i=0;i<len;i++)
	{
		int sign=str[i]-'a';
		if(p->next[sign]==NULL)
		{
			q=new trie();
			p->next[sign]=q;
			p=p->next[sign];
		}
		else
		{
			p=p->next[sign];			
		}
	}
	p->v=-1;
}

int find(trie *root,char *str,int i,int len)
{
	trie *p=root,*q;
	for(;i<len;i++)
	{
	
			int id=str[i]-'a';
			p=p->next[id];
			if(p==NULL)
			{
				return 0;
			}	
	}
	if(p->v==-1)
	{
		return 1;
	}
	else
	{
		return 0;
	}
}

void del(trie *root)
{
	for(int i=0;i<26;i++)
	{
		if(root->next[i])
		{
			del(root->next[i]); 
		}
	}
	delete(root);
}

int main()
{
	root=new trie();
	int count=0;
	while(scanf("%s",s[count])!=EOF)
	{
		creat(root,s[count]);
		count++;
	}
	for(int i=0;i<count;i++)
	{
		int len1=strlen(s[i]);
		for(int j=1;j<len1;j++)
		{
		    if(find(root,s[i],0,j)&&find(root,s[i],j,len1))
		    {
		    	cout<<s[i]<<endl;
		    	break;
			}
		}
	}
	return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值