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.
You are to find all the hat’s words in a dictionary.
Only one case.
a ahat hat hatword hziee word
ahathatword
题目意思:给你一些单词,看能否由其中的两个组成另外一个单词,能就输出这个单词。
解题思路:利用字典树,将这些单词进行建树,然后再将他们输入进去进行查找,找到一个单词后,记录
这个点,再将这个点之后的单词提取出来,输入查找,若找到,那么这个两个单词组成的单词
便存在。
#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; }
569

被折叠的 条评论
为什么被折叠?



