c++前缀树代码

#include <iostream>
#include <string>
#include <map>
using namespace std;
class Node
{
public:
	int pass;
	int end;
	Node **next;
	//map<int, Node*> next;
	//用表存储(int)word[i],便可不局限于字母
	Node()
	{
		pass = 0;
		end = 0;
		//0  a  1   b   2   c    仅限字母
		next = new Node*[26];
		for (int i = 0; i < 26; i++)
		{
			next[i] = NULL;
		}
	}
	~Node()
	{
		cout << "Node 析构调用" << endl;
		for (int i = 0; i < 26; i++)
		{
			delete next[i];
		}
		delete next;
	}
};

class Trie        //前缀树
{
public:
	Node *root;
	Trie()
	{
		root = new Node;
	}
	void insert(string word)
	{
		if (word == "")
			return;
		Node *node = root;
		node->pass++;
		int path = 0;
		for (int i = 0; i < word.length(); i++)
		{
			path = word[i] - 'a';
			if (node->next[path] == NULL)
			{
				node->next[path] = new Node;
			}
			node = node->next[path];
			node->pass++;
		}
		node->end++;
	}
	int search(string word)
	{
		if (word == "")
		{
			return 0;
		}
		Node *node = root;
		int index = 0;
		for (int i = 0; i < word.length(); i++)
		{
			index = word[i] - 'a';
			if (node->next[index] == NULL)
			{
				return 0;
			}
			node = node->next[index];
		}
		return node->end;
	}
	int prefixNumber(string pre)
	{
		if (pre == "")
		{
			return 0;
		}
		Node* node = root;
		int index;
		for (int i = 0; i < pre.length(); i++)
		{
			index = pre[i] - 'a';
			if (node->next[index] == NULL)
			{
				return 0;
			}
			node = node->next[index];
		}
		return node->pass;
	}
	void wordDelete(string word)
	{
		int exist = search(word);
		if (exist == 0)
		{
			return;
		}
		int index;
		Node* node = root;
		node->pass--;
		int record = node->pass;
		Node* pre = node;
		for (int i = 0; i < word.length(); i++)
		{
			index = word[i] - 'a';
			node = node -> next[index];
			node->pass--;
			if (record == 0)
			{
				delete pre;
			}
			pre = node->next[index];
		}
		node->end--;
	}
	~Trie()
	{
		delete root;
	}
};
int main(void)
{
	Trie a;
	a.insert("app");
	a.insert("app");
	a.insert("app");
	a.insert("pear");
	a.insert("apple");
	a.insert("apple");
	int times = a.search("app");
	cout << times << endl;
	times= a.search("apple");
	cout << times << endl;
	times = a.prefixNumber("app");
	a.wordDelete("app");
	times = a.prefixNumber("app");
	cout << times << endl;
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值