#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;
}