#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;
}
前缀树C++实现(使用map的方式)
于 2023-06-06 17:17:35 首次发布