hdu1247 Hat’s Words ---- 字典树

原题链接: http://acm.hdu.edu.cn/showproblem.php?pid=1247


一:原题内容

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


二:分析理解

题意很清楚:就是给出若干个单词,找出其中能够由其它两个单词连接组合而成的单词。比如上面sample中的"ahat"能够由"a"和"hat"拼凑而成,"hatword"="hat"+"word".因此只需对每个单词进行切分,把切分得到的两个单词在原单词序列中查找,若能查到则符合条件。在这里为了降低查找的复杂度,采用Trie树存储原始单词序列。


三:AC代码

#define _CRT_SECURE_NO_DEPRECATE 
#define _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES 1 

#include<iostream>    
#include<algorithm>    

using namespace std;

struct Node
{
	bool word;
	Node* next[26];
	Node() 
	{ 
		word = false; 
		for (int i = 0; i < 26; i++)
			next[i] = nullptr;
	}
};

char ch[50005][55];
Node* root = new Node;

void insert(char* pCh)
{
	Node* p = root;
	while (*pCh != '\0')
	{
		if (p->next[*pCh - 'a'] == nullptr)
			p->next[*pCh - 'a'] = new Node;
		p = p->next[*pCh - 'a'];
		pCh++;
	}

	p->word = true;
}

bool findBehind(char* pCh)
{
	Node* p = root;
	while (*pCh != '\0')
	{
		if (p->next[*pCh - 'a'] == nullptr)
			return false;

		p = p->next[*pCh - 'a'];
		pCh++;
	}

	if (p->word == true)
		return true;

	return false;
}

bool find(char* pCh)
{
	Node* p = root;

	while (*pCh != '\0')
	{
		p = p->next[*pCh - 'a'];
		pCh++;

		/*if (p->word == true)
			return findBehind(pCh);*/

		//有点坑啊,这里忘记了,一个单词可能包括好几个单词,所以如果findBehind返回失败,
		//也应该继续往下查找而不是结束该单词的判断
		if (p->word == true && findBehind(pCh))
			return true;

	}

	return false;
}


int main()
{
	int c = 0;
	while (scanf("%s", ch[c])!=EOF)
	{
		insert(ch[c++]);
	}
	
	for (int i = 0; i < c; i++)
	{
		if (find(ch[i]))
			printf("%s\n", ch[i]);
	}

	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值