栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

前缀树C++的实现

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

前缀树C++的实现

C++前缀树
#include
#include
using namespace std;
//前缀树的生成
class TrieNode 
{
public:
	int pass;//代表经过
	int end;  //代表结尾
	TrieNode **nexts;  //标记路的数组

	TrieNode()
	{
		pass = 0;
		end = 0;
		nexts = new TrieNode*[26];
	}
};
class Trie :public TrieNode
{
public:
	TrieNode* root;
	Trie()
	{
		root = new TrieNode();
	}
	void insert(string word);
	int search(string word);
	int prefixNumber(string pre);
	void Delete(string word);
};
void  Trie::insert(string word)
{
	if (word.size()<=0)
	{
		return;
	}
	char *chs;
	strcpy(chs, word.c_str);
	TrieNode* node = root;
	node->pass++;
	int index = 0;
	for (int i = 0; i < word.size(); i++)
	{
		index = chs[i] - 'a';
		if (node->nexts[index] ==NULL)
		{
			node->nexts[index] = new TrieNode();
		}
		node = node->nexts[index];
		node->pass++;
	}
	node->end++;

}
int Trie::search(string word)
{
	if (word.size <= 0)
	{
		return;
	}
	char *chs;
	strcpy(chs, word.c_str);
	TrieNode*node = root;
	int index = 0;
	for (int i = 0; i < word.size(); i++)
	{
		index = chs[i] - 'a';
		if (node->nexts[index] == NULL)
		{
			return 0;
		}
		node = node->nexts[index];
	}
	return node->end;
}
int Trie::prefixNumber(string pre)
{
	if (pre.size() <= 0)
	{
		return 0;
	}
	char *chs;
	strcpy(chs, pre.c_str);
	TrieNode*node = root;
	int index = 0;
	for (int i = 0; i < pre.size(); i++)
	{
		index = chs[i] - 'a';
		if (node->nexts[index] == NULL)
		{
			return 0;
		}
		node = node->nexts[index];
	}
	return node->pass;
}
void Trie::Delete(string word)
{
	if (word == "")
	{
		return;
	}
	char *chs;
	strcpy(chs, word.c_str);
	TrieNode *node = root;
	TrieNode*tmp;
	int index = 0;
	int indext = 0;
	for (int i = 0; i < word.size(); i++)
	{
		index = chs[i] - 'a';
		tmp = node->nexts[index];
		if (--node->nexts[index]->pass == 0)
		{
			delete node->nexts[index];
		}
		node = tmp;
	}
	node->end--;
}
int main()
{

	system("pause");
	return 0;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/853802.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号