-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrietree2.cpp
More file actions
121 lines (105 loc) · 3.44 KB
/
Copy pathtrietree2.cpp
File metadata and controls
121 lines (105 loc) · 3.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;
class Trie {
public:
struct TrieNode {
int pass; // 经过这个节点的次数 (原代码叫 path)
int end; // 以这个节点结尾的次数
unordered_map<int, TrieNode*> nexts;
TrieNode() {
pass = 0;
end = 0;
}
// 析构函数:递归释放内存
~TrieNode() {
for (auto& pair : nexts) {
// 修复:删除非空的子节点
if (pair.second != nullptr) {
delete pair.second;
}
}
}
};
private:
TrieNode* root;
public:
Trie() {
root = new TrieNode();
}
~Trie() {
if (root != nullptr) {
delete root;
root = nullptr;
}
}
void insert(const string& word) {
TrieNode* node = root;
node->pass++; // 根节点的 pass 也要增加
for (int i = 0; i < word.length(); i++) {
int path = word[i] - 'a'; // 这里用 path 表示路径索引
if (node->nexts.find(path) == node->nexts.end()) {
node->nexts[path] = new TrieNode();
}
node = node->nexts[path];
node->pass++;
}
node->end++;
}
void erase(const string& word) {
if (countWordEqualTo(word) > 0) { // 确认存在才删除
TrieNode* node = root;
node->pass--; // 修复:根节点的 pass 也要减少
for (int i = 0; i < word.length(); i++) {
int path = word[i] - 'a';
TrieNode* next = node->nexts[path];
if (--next->pass == 0) {
// 如果下个节点的引用计数为0,直接释放内存并从 map 移除
delete next;
node->nexts.erase(path);
return;
}
node = next;
}
node->end--;
}
}
// 查询单词出现的次数
int countWordEqualTo(const string& word) {
TrieNode* node = root;
for (int i = 0; i < word.length(); i++) {
int path = word[i] - 'a';
if (node->nexts.find(path) == node->nexts.end()) {
return 0;
}
node = node->nexts[path];
}
return node->end;
}
// 查询以前缀开头的单词数量
int countWordsStartingWith(const string& pre) {
TrieNode* node = root;
for (int i = 0; i < pre.length(); i++) {
int path = pre[i] - 'a';
if (node->nexts.find(path) == node->nexts.end()) {
return 0;
}
node = node->nexts[path];
}
// 修复:这里返回 pass (经过次数),而不是 end
return node->pass;
}
};
// 测试用的 main 函数
int main() {
Trie trie;
trie.insert("apple");
trie.insert("apple");
trie.insert("app");
cout << "Count 'apple': " << trie.countWordEqualTo("apple") << endl; // 应输出 2
cout << "Start with 'app': " << trie.countWordsStartingWith("app") << endl; // 应输出 3
trie.erase("apple");
cout << "Count 'apple' after erase: " << trie.countWordEqualTo("apple") << endl; // 应输出 1
return 0;
}