Hat’s Words
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 16086 Accepted Submission(s): 5737
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.
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.
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
ahathatword
题意:找出能够由两个单词组成的单词。
思路:只要将每个单词拆开来,一个个匹配,如果拆开的两个单词都有则是符合的。
代码:
#include <iostream> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <queue> using namespace std; int head,tail; typedef struct node { bool isStr; struct node *child[26]; }node,*Node; Node root; void insert(char *s) { Node next,temp; next=root; int n=strlen(s); int i; for(i=0;i<n;i++) { int z=s[i]-'a'; if(next->child[z]==NULL) { temp=new node; for(int j=0;j<26;j++) { temp->child[j]=NULL; } temp->isStr=false; next->child[z]=temp; } next=next->child[z]; } next->isStr=true; } bool search(char *s) { int i; Node next; next=root; for(i=0;s[i]!='\0';i++) { if(next->child[s[i]-'a']==NULL) return false; next=next->child[s[i]-'a']; } return next->isStr; } void release(Node root) { for(int i=0;i<26;i++) { if(root->child[i]!=NULL) release(root->child[i]); } free(root); } char c[50010][50]; int main() { root=new node; int i; for(i=0;i<26;i++) root->child[i]=NULL; root->isStr=false; int k=0; while(scanf("%s",c[k])!=EOF) { insert(c[k++]); } for(i=0;i<k;i++) { int len=strlen(c[i]); for(int j=1;j<len-1;j++) { char temp1[55]={'\0'},temp2[55]={'\0'}; strncpy(temp1,c[i],j); strncpy(temp2,c[i]+j,len-j); if(search(temp1)&&search(temp2)) { printf("%s\n",c[i]); break; } } } release(root); return 0; }