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
思路 : 搜索每一个单词,每一个单词是不是分为两半,分开考虑,依次判定就行;
代码
#include <cstdio>
#include <cstring>
#define MAX 50001
using namespace std;
char str[MAX][101];
int ch[MAX][101];
int word[MAX];//这里 记录单词数目这个数组没用上
int val[MAX];//标记是否为单词节点
int sz, n;
void init(){
sz = 1;
memset(ch[0], 0, sizeof(ch[0]));
memset(word, 0, sizeof(word));
}
int idx(char x) {return x - 'a';}
void insert(char *s){
int i, j, l = strlen(s);
int u = 0;
for(i = 0; i < l; i++)
{
int c = idx(s[i]);
if(!ch[u][c])
{
memset(ch[sz], 0, sizeof(ch[sz]));
val[sz] = 0;//不是单词节点
ch[u][c] = sz++;
}
u = ch[u][c];
word[u]++;
}
val[u] = 1;
}
bool find(char *s)//判断该字符串 是不是 字符串集里面的一个字符串
{
int i, j, l = strlen(s);
int u = 0;
for(i = 0; i < l; i++)
{
int c = idx(s[i]);
if(!ch[u][c]) return false;
u = ch[u][c];
}
return val[u];//最后一个是不是单词节点
}
int judge(char *s)//判断该字符串 能否由另外两个字符串构成
{
int i, j, l = strlen(s);
if(l == 1) return 0;
char front[MAX], after[MAX];
char convert[MAX];
strcpy(convert, s);
strrev(convert);
int k = 0;
for(i = 0; i < l; i++)
{
if(i == l-1)
break;
front[k++] = s[i];
front[k] = '\0';
convert[l-k] = '\0';
if(find(front))//前面一部分可以找到
{
strcpy(after, convert);
strrev(after);
if(find(after))//后面一部分可以找到
return 1;
}
}
return 0;
}
int main(){
n = 0;
init();
while(scanf("%s", str[n])!= EOF)
insert(str[n++]);
for(int i = 0; i < n; i++)
{
if(judge(str[i])) //查找成功
printf("%s\n", str[i]);
}
return 0;
}