Hat’s Words
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 4181 Accepted Submission(s): 1614
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
题目大意:
在所给的单词表中,按字典序输出符合条件的 hat's word ,条件为: hat's word 恰好由所给单词表中的另外两个单词拼接而成。
思路:
对每一个单词判断,该单词所分为的两个单词是否都在所给单词表中,由于单词的数量最大为50000,判断拆分出的单词是否在单词表中是比较耗时的,所以为了提高效率,这里把所给单词另外建立成一棵字典树。
#include <stdio.h>
#include <string.h>
#define MAX 26
#define SIZE 50005
#define LENGTH 100
typedef struct Trie_Node
{
Trie_Node *child[MAX];
bool flag; //标记是否为一个单词结尾
Trie_Node(void)
{
flag = false;
memset(child, NULL, sizeof(child));
}
}*Trie;
char wordList[SIZE][LENGTH];
void InitTrie(Trie &root)
{
root = new Trie_Node;
}
void Insert(Trie curNode, char *word)
{
int i, j;
for (i = 0; word[i] != '\0'; i++)
{
j = word[i] - 'a';
if (curNode->child[j] == NULL)
{
curNode->child[j] = new Trie_Node;
}
curNode = curNode->child[j];
}
curNode->flag = true;
}
bool LookUp(Trie curNode, char *word)
{
int i, j;
for (i = 0; word[i] != '\0'; i++)
{
j = word[i] - 'a';
if (curNode->child[j] == NULL)
{
return false;
}
curNode = curNode->child[j];
}
return curNode->flag;
}
void HatsWord(Trie root, int size)
{
int i, j, k;
Trie curNode = NULL;
for (i = 0; i < size; i++)
{
curNode = root;
for (j = 0; wordList[i][j] != '\0'; j++)
{
//判断单词的前一部分所组成的单词是否已经出现在字典中
if (curNode->flag)
{
//判断剩下部分所组成的单词是否也在字典中
if (LookUp(root, &wordList[i][j]))
{
puts(wordList[i]); break;
}
}
k = wordList[i][j] - 'a';
if (curNode->child[k] == NULL)
{
break;
}
curNode = curNode->child[k];
}
}
}
int main(void)
{
int i;
Trie dict = NULL;
InitTrie(dict);
for (i = 0; scanf("%s", wordList[i]) != EOF; i++)
{
Insert(dict, wordList[i]);
}
HatsWord(dict, i);
return 0;
}
寻找Hat's Words
本文介绍了一种算法,用于从字典中找出所有Hat's Words,即由字典中其他两个单词拼接而成的单词。通过构建字典树来提高查找效率。
528

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



