Hat’s Words
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 307 Accepted Submission(s): 141
Problem Description
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
题目要求就是根据输入的单词中来判断这个单词是不是由其他两个单词所构成的 (一开始我以为这是判断这个丹墀是不是有hat和另外一个单词构成 后来一提交就是WA 看了别人的解题思路以后感觉心好痛 然后就用字典树来做了)
字典树:
首先需要建树
建完树以后就逐层的去找 如果要查找的元素的第一个元素和根节点的元素的值不一样 那吗这个单词肯定不在这个字典树 如果相等就一层层的向下进行比较 直至比较完成
#include<iostream>
#include<algorithm>
#include<string>
#include<string.h>
#include<stdio.h>
#include<stack>
#include<stdlib.h>
#include<vector>
using namespace std;
typedef struct node
{
int isword ;
struct node *next[27];
}node;
void Insert(node *root,string str)
{
node *p = root;
node *q;
for(int i =0;i<str.size();i++)
{
int id = str[i] -'a';
if(p->next[id]==NULL)//如果这个节点不存在只需要将其存下来就行了
{
node *q = (node *)malloc(sizeof(node));
q->isword = 0;//初始化
memset(q->next,0,sizeof(q->next));//指针初始化为NULL
p->next[id] = q;
}
p =p->next[id];//如果这个节点之前已经存在怎只需要移动到下一次层
}
p->isword =1;//单词结束的标志
}
int serach(node *r,string str)
{
node *p = r;
for(int i =0;i<str.size();i++)
{
int id = str[i] -'a';
if(p->next[id]==NULL)//如果所查找的元素不在这一层里面 则不需要继续查了 呢吗下面也会没有的
return 0;
p = p->next[id];//否则就逐层往下面去找
}
return p->isword;//最终返回是不是单词
}
void del(node *root)//这一步是动态删除节点 防止内存不够的情况
{
for(int i =0;i<27;i++)
if(root->next[i]!=NULL)
free(root->next[i]);
free(root);
}
int main()
{
vector<string> pq;
string str;
node *r = (node *)malloc(sizeof(node));
r->isword = 0;
memset(r->next,0,sizeof(r->next));
while(cin>>str)
{
pq.push_back(str);
Insert(r,str);
}
for(int i =0;i<pq.size();i++)
{
string str = pq[i];
int len = str.size();
for(int j =1;j<=len-1;j++)
{
string tmp = str.substr(0,j);
//cout<<tmp<<" ";
string tmp2 = str.substr(j);
// cout<<tmp2<<endl;
if(serach(r,tmp)&&serach(r,tmp2)){
cout<<str<<endl;
break;
}
}
}
del(r);
return 0;
}