搜索引擎的搜索关键字提示功能——Trie树

个人微信公众号:程序员宅急送
在这里插入图片描述

百度、Google我相信大家都用过,在搜索框中输入一个字就能弹出很多可选的关键词,如下图

在这里插入图片描述

像这种关键词搜索功能最底层的数据结构就是我今天要说的:Trie树。

一、什么是Trie树?

简单点说就是个多叉树。我们把每个字符串中重合的前缀合并在一起形成的多叉树!

二、画个图

说的话有些麻烦,我们直接来看图!

在这里插入图片描述

三、代码实现

typedef struct _TrieNode
{
	string data;
	bool isEnding = false;
	struct _TrieNode* children[26] = {0};
}TrieNode;
class Trie 
{
public:
	TrieNode* initTrie()
	{
		TrieNode* rootNode = new TrieNode;
		rootNode->data = '/';
		return rootNode;
	}
	void insertNode(TrieNode* rootNode,string str)
	{
		TrieNode* cur = rootNode;
		int len = str.size();
		for (int i =0;i<len;++i)
		{
			int index = str[i] - 'a';
			if (cur->children[index] != 0)
			{
				cur = cur->children[index];
			}
			else
			{
				TrieNode* newNode = new TrieNode;
				newNode->data = str[i];
				cur->children[index] = newNode;
				cur = newNode;
			}
		}
		cur->isEnding = true;
	}
	void printTrie(TrieNode* cur,string str)
	{
		if (cur->isEnding != true)
		{
			for (int i = 0; i < 26; ++i)
			{
				if (cur->children[i] != 0)
				{
					string newStr = str;
					newStr += cur->children[i]->data;
					printTrie(cur->children[i], newStr);
				}
				
			}
		}
		else
		{ 
			cout << str.c_str() << endl;
		}
		
	}
	void search(TrieNode* rootNode, string str)
	{
		TrieNode* cur = rootNode;
		int len = str.size();
		for (int i = 0; i < len; ++i)
		{
			int index = str[i] - 'a';
			if (cur->children[index] != 0)
			{
				string dd = cur->children[index]->data;
				cur = cur->children[index];
			}
			else
			{
				cout << "can not find the string."<<endl;
			}
		}
		if (cur->isEnding)
		{
			cout << str.c_str() << endl;
		}
		else
		{
			printTrie(cur, str);
		}
	}
};
int main()
{
	Trie* t1 = new Trie;
	TrieNode* root= t1->initTrie();
	t1->insertNode(root, "hello");
	t1->insertNode(root, "her");
	t1->insertNode(root, "hi");
	t1->insertNode(root, "how");
	t1->insertNode(root, "so");
	t1->insertNode(root, "see");
	t1->search(root,"he");
	system("pause");
	return 0;
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值