Trie树 键树应用

给一个字典,然后给定一个字符串,求字典中所有以该字符串为前缀的单词。会有多次查询,要求通过预处理建立一个查询结构。

可假设字典仅含有小写字母。


struct Node
{
	bool isTail;
	Node *child[26];
	Node()
	{
		isTail = false;
		for(int i = 0; i < 26; ++i)
			child[i] = NULL;
	}
};
Node *ROOT;
void addWord(string &word)
{
	Node *cur = ROOT;
	for(int i = 0; i < word.size(); ++i)
	{
		char ch = word[i];
		if(cur->child[ch - 'a'] == NULL)
			cur->child[ch - 'a'] = new Node();
		cur = cur->child[ch - 'a'];
	}
	cur->isTail = true;
}
void BuildTree(vector<string> &words)
{
	ROOT = new Node();
	for(vector<string>::size_type i = 0; i != words.size(); ++i)
		addWord(words[i]);
}

Node *SearchNode(string &prefix)
{
	Node *ret = ROOT;
	for(string::size_type i = 0; i != prefix.size(); ++i)
		if(NULL == ret->child[prefix[i] - 'a'])
			return NULL;
		else
			ret = ret->child[prefix[i] - 'a'];
	return ret;
}

void dfs(Node *start, vector<string> &ret, string prefix)
{
	if(start->isTail)
		ret.push_back(prefix);
	for(int i = 0; i < 26; ++i)
		if(NULL != start->child[i])
		{
			prefix.push_back((char)('a' + i));
			dfs(start->child[i], ret, prefix);
		}
}

vector<string> getWords(string &prefix)
{
	Node *start = SearchNode(prefix);
	vector<string> ret;
	if(NULL == start)
		return ret;
	dfs(start, ret, prefix);
	return ret;
}

int main()
{	
	vector<string> words;
	words.push_back("abcsdfa");
	words.push_back("sdfwsd");
	words.push_back("abcsdrfw");
	words.push_back("fafse");
	BuildTree(words);
	string prefix("abc");
	vector<string> res = getWords(prefix);
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值