左神算法-前缀树【c++实现】

#include <iostream>
#include <string>
using namespace std;
struct Node
{
	int path;
	int end;
	int count = 0;
	Node* nexts[26];
};
class Trie
{
private: 
	Node *root;
public:
	Trie(){
		root = new Node();//每个Node后面都挂26个Node
	}
	void insert(string word)
	{
		if (word.empty())
			return ;
		Node* ptr = root;
		int index = 0;
		for (int i = 0; i < word.size(); i++)
		{
			index = word[i] - 'a';
			if (ptr->nexts[index] == nullptr)
				ptr->nexts[index] = new Node();
			ptr = ptr->nexts[index];
			(*ptr).path++;
		}
		(*ptr).end++;
	}
	int search(string word)
	{
		if (word.empty())
			return 0;
		Node* ptr = root;
		int index = 0;
		for (int i = 0; i < word.size(); i++)
		{
			index = word[i] - 'a';
			ptr = ptr->nexts[index];
		}
		return (*ptr).end;
	}
	void delete_(string word)
	{
		if (search(word) != 0)
		{
			Node* ptr = root;//每次都需要回到根节点
			int index = 0;
			for (int i = 0; i < word.size(); i++)
			{
				index = word[i] - 'a';
				if (--(*(ptr->nexts[index])).path == 0) {//判断时已经相减
					ptr->nexts[index] = nullptr;//重新置空
					return;
				}
				ptr = ptr->nexts[index];
			}
			ptr->end--;
		}
	}
	int prefixNumber(string pre)
	{
		if (pre.empty())
			return 0;
		Node* ptr = root;//每次都需要回到根节点
		int index = 0;
		for (int i = 0; i < pre.size(); i++)
		{
			index = pre[i] - 'a';
			if (ptr->nexts[index]== nullptr) {
				return 0;
			}
			ptr = ptr->nexts[index];
			return ptr->path;
		}
	}
};
int main()
{
	Trie sol;
	sol.insert("hello ya");
	sol.insert("how are you");
	sol.insert("hello ya");
	sol.insert("hello ya");
	sol.insert("hello ya");
	sol.insert("how do you do");
	sol.insert("what's up");
	sol.insert("whoo");
	sol.insert("bye");
	cout<<"repeated word num:"<<sol.search("hello ya")<<endl;
	cout << "repeated prefix num:" << sol.prefixNumber("wh") << endl;;
	sol.delete_("hello ya");
	cout << "repeated word num:" << sol.search("hello ya") << endl;
	system("pause");
	return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值