数据结构之字典树
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
You are to find all the hat’s words in a dictionary.
Only one case.
a ahat hat hatword hziee word
ahat hatword
这题使用普通字典树,即可完成,先对单词进行插入操作,更新字典树,然后在对每个单词查询的时候将其分为两部分,一部分为前缀,一部分为后缀,随后在字典树中查询前缀与后缀能否同时存在,同时存在说明该单词有两个单词拼在一起的
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
typedef struct node{
int flag;
struct node *next[26];
}Trie;
void insertTrie(Trie *root,char *str){//字典树的更新操作
if(root==NULL||*str=='\0')
return;
Trie *p = root;
while(*str!='\0'){
if(p->next[*str-'a']==NULL){//当前结点为空,
Trie *q = (Trie *)malloc(sizeof(Trie));//开辟内存空间
q->flag=0;
for(int i=0;i<26;i++){
q->next[i]=NULL;
}
p->next[*str-'a']=q;
p=p->next[*str-'a'];//使p指向新开辟的内存空间
}
else p=p->next[*str-'a'];
str=str+1;
}
p->flag=1;
}
int findTrie(Trie *root,char *str){
Trie *p = root;
while(*str!='\0'){
if(p->next[*str-'a']==NULL)//当前结点为空
return 0;
p=p->next[*str-'a'];
str=str+1;
}
return p->flag;
}
char cstr[50050][100];
int main(){
char c1[100],c2[100];
Trie *root = (Trie *)malloc(sizeof(Trie));//开辟根节点内存空间
root->flag=0;
for(int i=0;i<26;i++){
root->next[i]=NULL;
}
int cnt=0;
while(scanf("%s",cstr[cnt])!=EOF){
insertTrie(root,cstr[cnt]);
cnt++;
}
memset(c1,'\0',sizeof(c1));//初始化c1,c2
memset(c2,'\0',sizeof(c2));
for(int i=0;i<cnt;i++){
for(int j=1;j<strlen(cstr[i]);j++){
strcpy(c1,cstr[i]);
c1[j]='\0';//将cstr中0~j字符串复制的c1
strcpy(c2,cstr[i]+j);//将cstr中j~最后字符串复制到c2
if(findTrie(root,c1)&&findTrie(root,c2)){
printf("%s\n",cstr[i]);
break;
}
}
}
return 0;
}