#include <iostream>
#include <string>
using namespace std;
/*
*Trie树 字典树C++实现
*/
class TrieNode {
public:
TrieNode() {
end = path = 0;
for (int i = 0; i < 26; i++) {
nexts[i] = NULL;
}
};
public:
int end;//以该字符结尾的单词个数
int path;//以该字符之前的字符串为前缀的单词个数
TrieNode* nexts[26];
};
//插入单词
void insert(TrieNode* head, const string& word) {
if (head && word.size()) {
TrieNode* node = head;
for (int i = 0; i < word.size(); i++) {
if (node->nexts[word[i] - 'a'] == NULL) {
node->nexts[word[i] - 'a'] = new TrieNode();
}
node->path++;
node = node->nexts[word[i] - 'a'];
}
node->end++;
//该情况是单词结尾的位置 前缀数也加1
node->path++;
}
}
//求word出现的次数
int wordTimes(TrieNode* head, const string& word) {
if (head && word.size()) {
TrieNode* node = head;
for (int i = 0; i < word.size(); i++) {
if (node->nexts[word[i] - 'a'] == NULL) {
return 0;
}
node = node->nexts[word[i] - 'a'];
}
return node->end;
}
return 0;
}
//求以word为前缀的单词数
int wordPrefix(TrieNode* head, const string& word) {
if (head && word.size()) {
TrieNode* node = head;
for (int i = 0; i < word.size(); i++) {
if (node->nexts[word[i] - 'a'] == NULL) {
return 0;
}
node = node->nexts[word[i] - 'a'];
}
return node->path;
}
return 0;
}
//删除trie中的一个word
void deleteWord(TrieNode* head, const string& word) {
if (wordTimes(head, word)) {
TrieNode* node = head;
for (int i = 0; i < word.size(); i++) {
//如果此时path为1 则之后所有的结点都可以直接删除
if (node->nexts[word[i]-'a']->path-- == 1) {
node = NULL;
return;
}
node = node->nexts[word[i] - 'a'];
}
node->end--;
}
}
字典树Trie---C++实现
最新推荐文章于 2024-04-25 14:04:23 发布