C++ 字符串判断:高效判断字符是否存在于给定字符串

本教程将引导您使用 C++ 编写程序,判断输入的字符是否存在于字符串 'gdufe' 中。我们将使用 unordered_set 数据结构来实现高效的字符查找。

以下是完整的 C++ 代码:cpp#include #include <unordered_set>

int main() { int t; std::cout << '请输入测试用例的数量t:' << std::endl; std::cin >> t;

std::unordered_set<char> target = {'g', 'd', 'u', 'f', 'e'};

for (int i = 0; i < t; ++i) {        char c;        std::cout << '请输入一个小写字母c:' << std::endl;        std::cin >> c;

    std::string result = 'NO';        if (target.count(c) > 0) {            result = 'YES';        }

    std::cout << result << std::endl;    }

return 0;}

代码说明:

  1. 引入头文件: 我们引入了 iostream 用于输入输出,unordered_set 用于创建字符集。2. 创建字符集: std::unordered_set<char> target = {'g', 'd', 'u', 'f', 'e'}; 创建了一个包含 'gdufe' 字符的无序集合。3. 循环处理输入: 代码使用循环处理多个测试用例。4. 判断字符是否存在: target.count(c) 用于检查字符 c 是否存在于字符集 target 中。如果存在,则 count(c) 返回大于 0 的值,否则返回 0。5. 输出结果: 根据判断结果输出 'YES' 或 'NO'。

优势:

  • 高效查找: unordered_set 使用哈希表实现,提供快速的查找操作,平均时间复杂度为 O(1)。* 简洁易懂: 代码简洁易懂,适合初学者学习。

总结:

本教程介绍了如何使用 C++ 和 unordered_set 数据结构高效判断字符是否存在于给定字符串中。希望本教程对您有所帮助!

C++ 字符串判断:高效判断字符是否存在于给定字符串

原文地址: https://www.cveoy.top/t/topic/NOQ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录