Hat’s Words
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 8843 Accepted Submission(s): 3171
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
这题就是输入n个字符串,然后查找其中某个字符串是不是由其他两个输入的字符串组成的。
思路:
把所有字符串存到一个数组里,再插入到字典树里。
然后再遍历每个单词,枚举每个单词的前半部分和后半部分,再搜索字典树。
由于开始没看懂题意。导致wrong了两次。最后看了别人的题解,才发现自己把题目理解的完全错了,我以为是找包含”hat“的所有单词。。被自己蠢哭了。
然后重写的代码,一次A,还是不难的。
代码:
#include <stdio.h> #include <string.h> #include <stdlib.h> struct Trie{ bool isWord ; Trie *next[26] ; }*root; char all[50010][100] ; void init(Trie *node) { node->isWord = false ; for(int i = 0 ; i < 26 ; ++i) { node->next[i] = NULL ; } } void insert(char s[]) { int len = strlen(s) ; Trie *t = root ; for(int i = 0 ; i < len ; ++i) { if(t->next[s[i]-'a'] == NULL) { Trie *next = (Trie *)malloc(sizeof(Trie)); init(next) ; t->next[s[i]-'a'] = next ; } t = t->next[s[i]-'a'] ; } t->isWord = true ; } bool search(char s[]) { int len = strlen(s) ; Trie *t = root ; for(int i = 0 ; i < len ; ++i) { if(t->next[s[i]-'a']) { t = t->next[s[i]-'a'] ; } else { return false ; } } if(t->isWord) { return true ; } return false ; } void del(Trie *t) { for(int i = 0 ; i < 26 ; ++i) { if(t->next[i] != NULL) { del(t->next[i]) ; } } free(t) ; } int main() { char word[100] ; root = (Trie *)malloc(sizeof(Trie)) ; init(root) ; int index = 0 ; while(gets(word) != NULL) { strcpy(all[index++],word) ; insert(word) ; } for(int i = 0 ; i < index ; ++i) { int len = strlen(all[i]) ; for(int j = 1 ; j < len ; ++j) { char a[100] , b[100] ; strncpy(a,all[i],j) ; a[j] = '\0' ; if(search(a)) { strncpy(b,all[i]+j,len-j) ; b[len-j] = '\0' ; if(search(b)) { puts(all[i]) ; break ; } } } } del(root) ; return 0 ; }
与君共勉