前缀树C++实现(使用map的方式)

#include<iostream>
#include<vector>
#include<string>
#include<map>
using namespace std;





//使用map来建立

struct Node {
public:
	int pass;
	int end;
	map<int, Node*>* nexts;

	Node() {
		this->pass = 0;
		this->end = 0;
		this->nexts = new map<int, Node*>();
	}
};


class Trie {
private:
	Node* root;
public:
	Trie() {
		this->root = new Node(); //初始化根节点
	}
	void insert(string str);
	int search(string str);
	void delete_bi(string str);
    int prefixNumber(string str);

};


//给一个字符串,获取以这个字符串为前缀的字符串数目
int Trie::prefixNumber(string str)
{
	if (str.empty()) {
		return 0;
	}
	string::iterator it = str.begin();
	int index = 0;
	Node* node = this->root;
	while (it != str.end()) {
		index = (int)(*it);
		if (node->nexts->find(index) == node->nexts->end()) {
			//不存在
			return 0;
		}
		
		node = node->nexts->at(index);

		it++;
	}
	return node->pass;
}

void Trie::delete_bi(string str)
{
	//1.判断是否保存过这个字符串
	if (str.empty()) {
		return;
	}
	if (!this->search(str)) {
		return;
	}
	//2. 保存过这个字符串 进行遍历 每遍历到一个节点  pass -- 最后的时候进行 end -- 还要进行内存的释放

	Node* node = this->root;
	string::iterator it = str.begin();
	int index = 0;
	node->pass--;  //根节点的pass 
	while (it != str.end()) {
		index = (int)(*it);
		
		if (node->pass == 0) {
			Node* temp = node;
			node = node->nexts->at(index);
			delete temp;
			node->pass--;
		}
		else {
			node = node->nexts->at(index);
			node->pass--;
		}
		
		it++;

	}
	node->end--;
}

int Trie::search(string str) {
	if (str.empty()) {
		return 0;
	}
	//遍历
	string::iterator it = str.begin();
	int index = 0;
	Node* node = this->root;
	while (it != str.end()) {
		index = (int)(*it);
		if (node->nexts->find(index) == node->nexts->end()) {
			//不存在  return 0 
			return 0;
		}
		//存在
		node = node->nexts->find(index)->second;
		it++;
	}
	return node->end;  //返回加入过多少次 这个单词
}

void Trie::insert(string str) {
	if (str.empty()) {
		return;
	}
	//1.
	Node* node = this->root; //辅助指针
	node->pass++;
	int index = 0;
	string::iterator it = str.begin();
	while (it != str.end()) {
		index = (int)(*it);
		
		//若存在这个字符 则直接跳到下一个节点 否则新建节点
		if ((node->nexts)->find(index) == (node->nexts->end())) {
			//不存在
			(*node->nexts)[index] = new Node();
		}
		node = node->nexts->at(index);
		node->pass++;	
		it++;
	}
	node->end++;

}
int main() {
	
	Trie trie;
	trie.insert("suixueshuai");
	trie.insert("wangwnagwang");
	trie.insert("wangwnagwang");
	int times = trie.search("wangwnagwang");
	cout << "times:" << times << endl;
	bool is_have = trie.search("wangwnagwang");
	cout << "is_have:" << is_have << endl;
	trie.delete_bi("wangwnagwang");
	times = trie.search("wangwnagwang");
	cout << "times:" << times << endl;

	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

苹果香蕉柠檬c

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

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

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

打赏作者

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

抵扣说明:

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

余额充值