Hat’s Words
Time Limit : 2000/1000ms (Java/Other) Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 5 Accepted Submission(s) : 3
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
ahat hatword
1.将所有单词创建字典树
2.将每个单词拆分成两个,(如单词 ahat 依次拆分成 a,hat ; ah,at; aha,t; )依次判断拆分的两个单词是否存在与字典树
#define N 50005 #include<stdio.h> #include<string.h> #include<stdlib.h> typedef struct Tire { Tire * child[26]; bool flag; }Tire; Tire * root; void insert(char * s)//创建字典树 { Tire *p,*q=root; for(int i=0;i<strlen(s);i++) { if(q->child[s[i]-'a']) q = q->child[s[i]-'a']; else{ p = (Tire *)malloc(sizeof(Tire)); p->flag=0; for(int j=0;j<26;j++) p->child[j]=NULL; q->child[s[i]-'a'] = p; q = p; } } q->flag = 1;//标志为1的代表这里是某个单词的结尾 } bool find(char *s) { Tire * q=root; for(int i=0;i<strlen(s);i++){ if(q->child[s[i]-'a']) q = q->child[s[i]-'a']; else return false; } if(q->flag==1) return true;//在字典树中找到该单词 else return false; } int main() { char s[N][20],s1[20],s2[20]; root = (Tire *)malloc(sizeof(Tire)); for(int i=0;i<26;i++) root->child[i]=NULL; int k=0; while(scanf("%s",s[k])!=EOF ) insert(s[k++]); for(int i=0;i<k;i++){ for(int j=1;j<strlen(s[i]);j++){ for(int m=0;m<j;m++) s1[m]=s[i][m]; //将每个单词拆分成两个 s1[j] = '\0'; sscanf(s[i]+j,"%s",s2); if(find(s1)&&find(s2)) { //拆分的两个单词都存在与字典树 puts(s[i]); break; } } } return 0; }
别人的STL 简单代码,没用过,不懂!!!先贴着,学过STL 以后看,这个效率不高。。
#include <iostream> #include <string> #include <map> using namespace std; map <string, int> m_v; string str[50006]; int main() { int k(-1); while(cin >> str[++k]) { m_v[str[k]] = 1; } for(int i = 0; i <= k; i++) { int e = str[i].size()-1; for(int j = 1; j < e; j++) { string s1(str[i], 0, j); string s2(str[i], j); if(m_v[s1] == 1 && m_v[s2] == 1) { cout << str[i] << endl; break; } } } return 0; }