数据结构之-简单实现字典树

字典树:

又称单词查找树,Trie树,是一种树形结构,是一种哈希树的变种。典型应用是用于统计,排序和保存大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。它的优点是:利用字符串的公共前缀来节约存储空间,最大限度地减少无谓的字符串比较,查询效率比哈希表高。

字典树的基本功能是用来查询某个单词(前缀)在所有单词中出现次数的一种数据结构,它的插入和查询复杂度都为O(len),Len为单词(前缀)长度,但是它的空间复杂度却非常高,如果字符集是26个字母,那每个节点的度就有26个,典型的以空间换时间结构。
借用网上的图:不知道哪位博主的,先谢谢了。忘记地址了。

在这里插入图片描述

代码示例:

#include<iostream>
using namespace std;

int Trie[100][26] = {0};

int bFlag[1000] = { 0 };

int ncount = 1;
void InsertToTrie(char *str)
{
	int nLen = strlen(str);
	int nroot = 0;
	for (int i = 0; i < nLen;i++)
	{
		
		int id = str[i] - 'a';
		if (Trie[nroot][id] == 0)
		{
			//不存在,则加入
			Trie[nroot][id] = ncount++;			
		}
		
		//已经存在
		nroot = Trie[nroot][id] ;		
	}

	bFlag[ncount] = 1;
}

//查找某个字符串是否存在
bool Triefind(char *str)
{
	int nLen = strlen(str);
	int nroot = 0;
	for (int i = 0; i < nLen; i++)
	{

		int id = str[i] - 'a';
		if (Trie[nroot][id] == 0)
		{
			return false;
		}
	
		//已经存在
		
		nroot = Trie[nroot][id];
		
	}

	return bFlag[nroot+1];

}



void main()
{
	InsertToTrie("apple");
	InsertToTrie("apply");
	InsertToTrie("as");
	InsertToTrie("at");
	InsertToTrie("ok");
	InsertToTrie("cash");
	InsertToTrie("cat");

	bool ret = Triefind("applx");
	if (ret)
	{
		cout << "find applx\n";
	}
	else
	{
		cout << "no find applx!\n";
	}

	 ret = Triefind("apple");
	if (ret)
	{
		cout << "find apple\n";
	}
	else
	{
		cout << "no find apple!\n";
	}


ret = Triefind("cash");
	if (ret)
	{
		cout << "find cash\n";
	}
	else
	{
		cout << "no find cash!\n";
	}


	ret = Triefind("cat");
	if (ret)
	{
		cout << "find cat\n";
	}
	else
	{
		cout << "no find cat!\n";
	}

	ret = Triefind("asx");
	if (ret)
	{
		cout << "find asx\n";
	}
	else
	{
		cout << "no find asx!\n";
	}


	ret = Triefind("ok");
	if (ret)
	{
		cout << "find ok\n";
	}
	else
	{
		cout << "no find ok!\n";
	}


	

	system("pause");
}

结果:
在这里插入图片描述
重要的是理解思想,插入的思想。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

发如雪-ty

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值