Word List

周一考试了,单单单词查不完了,只好随便整理一下了

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用 C++ 和 Trie 数据结构解决该问题的代码: ```c++ #include <iostream> #include <string> #include <vector> using namespace std; class TrieNode { public: TrieNode() : is_word(false), children(26, nullptr) {} void insert(const string& word) { TrieNode* node = this; for (char c : word) { int index = c - 'a'; if (!node->children[index]) { node->children[index] = new TrieNode(); } node = node->children[index]; } node->is_word = true; } bool search(const string& word) const { const TrieNode* node = this; for (char c : word) { int index = c - 'a'; if (!node->children[index]) { return false; } node = node->children[index]; } return node->is_word; } private: bool is_word; vector<TrieNode*> children; }; int main() { TrieNode root; // 读取单词列表并将其插入到 Trie 中 string word; while (getline(cin, word)) { if (word.empty()) { break; } root.insert(word); } // 对于每个查询字符串,搜索 Trie 中以其为前缀的单词 string query; while (cin >> query) { cout << (root.search(query) ? "YES" : "NO") << endl; } return 0; } ``` 该程序首先定义了一个 TrieNode 类,用于表示 Trie 中的一个节点。每个节点包含一个布尔值 is_word,表示从根节点到该节点的路径上是否形成一个单词,以及一个长度为 26 的子节点数组 children,用于存储该节点的子节点。类中定义了两个方法:insert() 用于将一个单词插入到 Trie 中,search() 用于搜索 Trie 中是否存在以给定字符串为前缀的单词。 程序主函数首先创建一个 Trie 根节点,并读取一系列单词,并将它们插入到 Trie 中。然后,对于每个查询字符串,搜索 Trie 中以该字符串为前缀的单词。如果找到了这样的单词,则输出“YES”,否则输出“NO”。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值