hdu 1247 Hat’s Words 字典树,还是比较有意思的题目

本文介绍了一种算法,用于从字典中找出所有由两个其他单词拼接而成的单词(Hat's Words)。通过构建字典树并遍历单词来高效解决这一问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 ;
}

与君共勉

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值