ZBLOG

class TrieNode { public: std::unordered_map children; bool is_end = false; int weight = 0; }; class Trie { public: TrieNode* root; Trie() { root = new TrieNode(); } void insert(const std::string& word, int weig...

你已经实现了一个基本的Trie结构,并在TrieNode中添加了权重属性。下面是完整的代码,包括头文件和使用示例,展示如何插入带权重的单词并查找前缀。

Trie.h

  1. #ifndef TRIE_H
  2. #define TRIE_H
  3. #include <unordered_map>
  4. #include <string>
  5. class TrieNode {
  6. public:
  7. std::unordered_map<char, TrieNode*> children; // 子节点
  8. bool is_end = false; // 是否为单词结尾
  9. int weight = 0; // 权重
  10. };
  11. class Trie {
  12. public:
  13. TrieNode* root;
  14. Trie();
  15. void insert(const std::string& word, int weight);
  16. TrieNode* search_prefix(const std::string& prefix);
  17. };
  18. #endif // TRIE_H

Trie.cpp

  1. #include "Trie.h"
  2. // 构造函数,初始化根节点
  3. Trie::Trie() {
  4. root = new TrieNode();
  5. }
  6. // 插入单词及其权重到trie中
  7. void Trie::insert(const std::string& word, int weight) {
  8. TrieNode* node = root;
  9. for (char c : word) {
  10. if (!node->children.count(c)) {
  11. node->children[c] = new TrieNode();
  12. }
  13. node = node->children[c];
  14. }
  15. node->is_end = true; // 标记为单词结尾
  16. node->weight = weight; // 设置权重
  17. }
  18. // 查找给定前缀的最后一个节点
  19. TrieNode* Trie::search_prefix(const std::string& prefix) {
  20. TrieNode* node = root;
  21. for (char c : prefix) {
  22. if (!node->children.count(c)) return nullptr; // 找不到返回nullptr
  23. node = node->children[c];
  24. }
  25. return node; // 返回找到的前缀对应的节点
  26. }

使用示例

  1. #include <iostream>
  2. #include "Trie.h"
  3. int main() {
  4. // 创建一个trie实例
  5. Trie trie;
  6. // 插入一些带权重的热词
  7. trie.insert("hello", 5);
  8. trie.insert("world", 10);
  9. trie.insert("trie", 2);
  10. trie.insert("data", 8);
  11. trie.insert("structure", 3);
  12. // 测试搜索前缀
  13. auto result_node = trie.search_prefix("tri");
  14. if (result_node) {
  15. std::cout << "Found prefix 'tri'. Is end: " << result_node->is_end << ", Weight: " << result_node->weight << std::endl;
  16. } else {
  17. std::cout << "Prefix 'tri' not found." << std::endl;
  18. }
  19. auto result_node2 = trie.search_prefix("wo");
  20. if (result_node2) {
  21. std::cout << "Found prefix 'wo'. Is end: " << result_node2->is_end << ", Weight: " << result_node2->weight << std::endl;
  22. } else {
  23. std::cout << "Prefix 'wo' not found." << std::endl;
  24. }
  25. return 0;
  26. }

编译和运行

确保将所有代码放在适当的文件中,然后可以使用以下命令编译并运行:

  1. g++ -o trie_example main.cpp Trie.cpp -std=c++11
  2. ./trie_example

总结

以上代码实现了一个包含权重属性的Trie数据结构,可以用于高效地插入和查找带有额外信息(如权重)的字符串。这种数据结构在许多应用场景中非常有用,例如搜索建议、自动补全等。希望这能帮助你更好地理解和使用Trie!


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=22279

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?