问题:在百度或大型网站,你输入“中国”出现“中国制造”,“中国创造”,好多以”中国“为前缀的字符串
前阵子JPG跟ZPG聊到了这个问题,当时懵逼ing,啥事前缀树,今日学到了便来一个总结
前缀树顾名思义要的就是前缀
接下去就是代码怎么来实现一颗前缀树;
#include <iostream>
#include <string>
using namespace std;
struct TrieNode {
int path;
int end;
struct TrieNode *next[26]; //指针数组
};
class Trie {
private:
TrieNode* root;
public:
Trie() {
root = new TrieNode();
}
~Trie() {
delete root;
root = NULL;
}
//插入一个字符串
void insert(string word) {
if (word.length() == NULL) {
return;
}
TrieNode* node = root;
int index = 0;
for (int i = 0; i < word.length(); i++) {
index = word[i] - 'a';
if (node->next[index] == NULL) {
node->next[index] = new TrieNode();
}
node = node->next[index];
node->path++;
}
node->end++;
}
//查找一个字符串
int search(string word) {
if (word.length() == 0) {
return 0;
}
TrieNode* 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;
}
//删除一个字符串
void deleteword(string word) {
if (search(word) == 0) {
return;
}
else {
TrieNode* node = root;
int index = 0;
for (int i = 0; i < word.length(); i++) {
index = word[i] - 'a';
if (--node->next[index]->path == 0) {
return;
}
node = node->next[index];
}
node->end--;
}
}
//查看这个前缀是否有在这个树里面
int prefixNumber(string pre) {
if (pre.length() == 0) {
return 0;
}
TrieNode* node = root;
int index = 0;
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->path;
}
};
int main() {
Trie* a = new Trie();
cout << a->search("cai") << endl;
a->insert("cai");
a->insert("cai");
a->insert("cai");
a->deleteword("cai");
cout << a->search("cai") << endl;
cout << a->prefixNumber("ca") << endl;
system("pause");
}