博客
关于我
Hat’s Words(字典树)
阅读量:620 次
发布时间:2019-03-13

本文共 1085 字,大约阅读时间需要 3 分钟。

为了解决这个问题,我们需要找出所有可以被分解为恰好两个其他词组成的词,这些词被称为“帽子的词”。我们可以使用哈希表来快速判断一个子串是否存在,从而高效地解决这个问题。

方法思路

  • 读取输入并构建哈希表:首先读取所有词,并将它们存储在一个哈希表中,以便快速查找。
  • 检查每个词:对于每个词,尝试所有可能的分割点,将其分成前后两部分,检查这两部分是否都存在于哈希表中。
  • 收集结果:将满足条件的帽子的词收集起来,排序后输出。
  • 解决代码

    #include 
    #include
    #include
    #include
    using namespace std;int main() { unordered_map
    word_map; vector
    words; string word; while (cin >> word) { words.push_back(word); word_map[word] = true; } vector
    results; for (auto &w : words) { int len = w.length(); for (int i = 1; i < len; ++i) { string prefix = w.substr(0, i); string suffix = w.substr(i); if (word_map.find(prefix) != word_map.end() && word_map.find(suffix) != word_map.end()) { results.push_back(w); break; } } } sort(results.begin(), results.end()); for (auto &r : results) { cout << r << endl; } return 0;}

    代码解释

  • 读取输入:使用unordered_map存储所有词,vector存储所有读取的词。
  • 构建哈希表:将每个词插入到哈希表中,以便快速查找。
  • 检查分割点:对于每个词,遍历所有可能的分割点,检查分割后的前缀和后缀是否都存在于哈希表中。如果存在,则将该词加入结果列表。
  • 排序和输出:对结果列表进行排序,并按顺序输出每个帽子的词。
  • 这个方法通过使用哈希表进行快速查找,确保了在合理的时间内解决问题,适用于输入规模较大的情况。

    转载地址:http://aueaz.baihongyu.com/

    你可能感兴趣的文章
    NodeJs学习笔记001--npm换源
    查看>>
    Nodejs教程09:实现一个带接口请求的简单服务器
    查看>>
    Nodejs简介以及Windows上安装Nodejs
    查看>>
    nodejs系列之express
    查看>>
    nodejs配置express服务器,运行自动打开浏览器
    查看>>
    Node中的Http模块和Url模块的使用
    查看>>
    Node入门之创建第一个HelloNode
    查看>>
    Node出错导致运行崩溃的解决方案
    查看>>
    node安装及配置之windows版
    查看>>
    Node提示:error code Z_BUF_ERROR,error error -5,error zlib:unexpected end of file
    查看>>
    Node读取并输出txt文件内容
    查看>>
    NOIp2005 过河
    查看>>
    NOIp模拟赛二十九
    查看>>
    NOPI读取Excel
    查看>>
    NoSQL&MongoDB
    查看>>
    NotImplementedError: Cannot copy out of meta tensor; no data! Please use torch.nn.Module.to_empty()
    查看>>
    npm error MSB3428: 未能加载 Visual C++ 组件“VCBuild.exe”。要解决此问题,1) 安装
    查看>>
    npm install digital envelope routines::unsupported解决方法
    查看>>
    npm install 报错 ERR_SOCKET_TIMEOUT 的解决方法
    查看>>
    npm install报错,证书验证失败unable to get local issuer certificate
    查看>>