hdu 1247 Hat’s Words 字典树

典型的字典树:

//思路:单词是小写的

//1)把所有的单词添加到字典树中

//2)然后针对每一个单词,把这个单词分成2个部分,分别在字典树中查询,如果同时存在则输出该单词,否则继续分成2个部分

#include <iostream>
#include <algorithm>
using namespace std;

#define N 32
#define SIZE 26
#define LISTSIZE 50010

typedef struct WordList_
{
	char str[N];
}WordList[LISTSIZE];

typedef struct Node_
{
	int is_word;
	Node_ * next[SIZE];

	Node_()
	{
		is_word = 0;
		for(int i = 0;i < SIZE;i++)
		{
			next[i] = 0;
		}
	}

}Node;


Node * root = 0;

WordList diclist;
WordList wlist;
bool cmp(WordList_ a, WordList_ b)
{
	return strcmp(a.str, b.str) < 0;
}

int tree_insert(char * word)
{
	if (root == 0)
	{
		root = new Node();
	}

	int len = strlen(word), i, site;
	Node * tmpNode = root;
	

	for(i = 0;i < len;i++)
	{
		site = word[i] - 'a';
		if (tmpNode->next[site] == 0)
		{
			tmpNode->next[site] = new Node();
		}

		tmpNode = tmpNode->next[site];
	}

	tmpNode->is_word = 1;
	return 0;
}

int tree_search(char * word)
{
	int len = strlen(word);
	int site;
	Node * tmpNode =  root;
	for(int i = 0;i < len;i++)
	{
		site = word[i] - 'a';
		if (tmpNode->next[site] == 0)
		{
			return 0;
		}
		tmpNode = tmpNode->next[site];
	}

	return tmpNode->is_word;

}

bool tree_delete(char * str)
{
	Node * tmpNode = root;
	int len = strlen(str);
	int i, site;
	for (i = 0;i < len;i++)
	{
		site = str[i] - '0';
		if (tmpNode->next[site] == 0)
		{
			return 0;
		}
		tmpNode = tmpNode->next[site];
	}

	if (tmpNode->is_word == 1)
	{
		tmpNode->is_word = 0;
	}
	else
	{
		return false;
	}

	return true;
}

void tree_clear(Node * root)
{
	if (root == 0)
	{
		return;
	}
	int i ;
	for ( i = 0;i < 10;i++)
	{
		if (root->next[i] != 0)
		{
			Node * tmpNode = root;
			root = root ->next[i];
			tree_clear(root);

			root = tmpNode;
		}
	}

	if (i == 10)
	{
		delete root;
		root = 0;
	}
}

int main()
{
	int t, n = 0, i, j, k,len;
	char left[N], right[N];
	int wlistlen = 0;

	while (scanf("%s", diclist[n].str) != EOF)
	{
		tree_insert(diclist[n].str);
		n++;
	}

	for (int i = 0; i < n;i++)
	{
		len = strlen(diclist[i].str);

		if (len < 2)
		{
			continue;
		}

		for(j = 1;j < len-1;j++)
		{
			strncpy(left, diclist[i].str, j);
			left[j] = 0;
			strncpy(right, diclist[i].str + j, len - j);
			right[len - j] = 0;

			if (tree_search(left) && tree_search(right))
			{
				strcpy(wlist[wlistlen++].str, diclist[i].str);
				break;
			}
		
		}
	}

	sort(wlist, wlist + wlistlen, cmp);

	for (int i = 0;i < wlistlen;i++)
	{
		printf("%s\n", wlist[i].str);
	}

	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值