你已经实现了一个基本的Trie结构,并在TrieNode
中添加了权重属性。下面是完整的代码,包括头文件和使用示例,展示如何插入带权重的单词并查找前缀。
Trie.h
#ifndef TRIE_H
#define TRIE_H
#include <unordered_map>
#include <string>
class TrieNode {
public:
std::unordered_map<char, TrieNode*> children; // 子节点
bool is_end = false; // 是否为单词结尾
int weight = 0; // 权重
};
class Trie {
public:
TrieNode* root;
Trie();
void insert(const std::string& word, int weight);
TrieNode* search_prefix(const std::string& prefix);
};
#endif // TRIE_H
Trie.cpp
#include "Trie.h"
// 构造函数,初始化根节点
Trie::Trie() {
root = new TrieNode();
}
// 插入单词及其权重到trie中
void Trie::insert(const std::string& word, int weight) {
TrieNode* node = root;
for (char c : word) {
if (!node->children.count(c)) {
node->children[c] = new TrieNode();
}
node = node->children[c];
}
node->is_end = true; // 标记为单词结尾
node->weight = weight; // 设置权重
}
// 查找给定前缀的最后一个节点
TrieNode* Trie::search_prefix(const std::string& prefix) {
TrieNode* node = root;
for (char c : prefix) {
if (!node->children.count(c)) return nullptr; // 找不到返回nullptr
node = node->children[c];
}
return node; // 返回找到的前缀对应的节点
}
使用示例
#include <iostream>
#include "Trie.h"
int main() {
// 创建一个trie实例
Trie trie;
// 插入一些带权重的热词
trie.insert("hello", 5);
trie.insert("world", 10);
trie.insert("trie", 2);
trie.insert("data", 8);
trie.insert("structure", 3);
// 测试搜索前缀
auto result_node = trie.search_prefix("tri");
if (result_node) {
std::cout << "Found prefix 'tri'. Is end: " << result_node->is_end << ", Weight: " << result_node->weight << std::endl;
} else {
std::cout << "Prefix 'tri' not found." << std::endl;
}
auto result_node2 = trie.search_prefix("wo");
if (result_node2) {
std::cout << "Found prefix 'wo'. Is end: " << result_node2->is_end << ", Weight: " << result_node2->weight << std::endl;
} else {
std::cout << "Prefix 'wo' not found." << std::endl;
}
return 0;
}
编译和运行
确保将所有代码放在适当的文件中,然后可以使用以下命令编译并运行:
g++ -o trie_example main.cpp Trie.cpp -std=c++11
./trie_example
总结
以上代码实现了一个包含权重属性的Trie数据结构,可以用于高效地插入和查找带有额外信息(如权重)的字符串。这种数据结构在许多应用场景中非常有用,例如搜索建议、自动补全等。希望这能帮助你更好地理解和使用Trie!
内容由零声教学AI助手提供,问题来源于学员提问