trie树的应用:查找hatword

Hat’s Words

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
拿hatword,这个例子来说吧,这个单词可以分成两外两个单词,就是hat和word,hat是在我们给定的样例中能找到的,同时word也能找到。那么hatword这个单词就符合要求。同时还可以察觉到,hat是hatword的一个前缀,判断一个单词是不是另一个单词的前缀有很多办法,一种是按顺寻遍历第一个字符串,看所有字符在第二个字符串中是否出现而且顺序与自身相同。还可以想到另外一种判断方法,那就是前缀树即trie索引树。前一种判断的方法所所用的时间是O(N),二第二种方法可以在O(lgn)的时间内完成。如果我们对hat进行判断,得到hat是hatword的前缀,那么剩下的就好办了,把剩下的字符分离出来,作为独立的一个单词,然后在字典出中查找,如果找到,那么说明hatword是满足题目要求的单词。下面给出分析的代码:

#include<iostream>
#include<string.h>
using namespace std;
#define MAX_SIZE 26
typedef struct trie_node{
	bool is_terminated;
	char data;
	struct trie_node *child[MAX_SIZE];
}TrieNode, *TrieTree;
TrieNode *create_node(char c) {
	TrieNode *temp = (TrieNode*)malloc(sizeof(TrieNode));
	temp->is_terminated = false;
	temp->data = c;
	for(int i = 0;i < MAX_SIZE; i++)
		temp->child[i] = NULL;
	return temp;
}
void trie_insert(TrieTree *T, char *s) {
	TrieNode *p = *T;
	while(*s) {
		if(p->child[*s - 'a'] == NULL) {
			p->child[*s - 'a'] = create_node(*s);
		}
		p = p->child[*s - 'a'];
		s++;
	}
	p->is_terminated = true;
}
bool trie_search(TrieTree T, char *s) {
	TrieNode *p = T;
	while(p && *s) {
		if(p->child[*s - 'a'] == NULL) {
			return false;
		} else {
			p = p->child[*s - 'a'];
			s++;
		}
	}
	return (*s == '\0') && p->is_terminated;
}
bool find_hat_word(TrieTree T, char *s) {
	TrieNode *p = T;
	while(p && *s) {
		if(p->is_terminated) {
			if(trie_search(T, s)) {
				return true;
				break;
			}
		}
		p = p->child[*s - 'a'];
		s++;
	}
	return false;
}
void main() {
	TrieTree T = create_node(' ');
	char *s[]= {"a", "ahat", "hat", "hatword", "hziee", "word", "test", "case", "testcase"};
	int num = sizeof(s) /sizeof(char*);
	for(int i =0;i < num; i++)
		trie_insert(&T, s[i]);
	for(i = 0; i < num; i++)
		if(find_hat_word(T, s[i]))
			cout << s[i] << endl;
}
    原文作者:Trie树
    原文地址: https://blog.csdn.net/zzran/article/details/8253355
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞