博客
关于我
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/

    你可能感兴趣的文章
    NMAP网络扫描工具的安装与使用
    查看>>
    NMF(非负矩阵分解)
    查看>>
    nmon_x86_64_centos7工具如何使用
    查看>>
    NN&DL4.1 Deep L-layer neural network简介
    查看>>
    NN&DL4.3 Getting your matrix dimensions right
    查看>>
    NN&DL4.7 Parameters vs Hyperparameters
    查看>>
    NN&DL4.8 What does this have to do with the brain?
    查看>>
    nnU-Net 终极指南
    查看>>
    No 'Access-Control-Allow-Origin' header is present on the requested resource.
    查看>>
    NO 157 去掉禅道访问地址中的zentao
    查看>>
    no available service ‘default‘ found, please make sure registry config corre seata
    查看>>
    No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
    查看>>
    no connection could be made because the target machine actively refused it.问题解决
    查看>>
    No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
    查看>>
    No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
    查看>>
    No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
    查看>>
    No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
    查看>>
    No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
    查看>>
    No module named 'crispy_forms'等使用pycharm开发
    查看>>
    No module named cv2
    查看>>