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

    你可能感兴趣的文章
    Python 3.5、ldap3 和 modify_password()
    查看>>
    python 3.6.8 升级至3.9版本升级
    查看>>
    Python 3.9 到 Python 3.12 的发展历程与区别
    查看>>
    python 32位和64位的区别在哪
    查看>>
    Python 3:何时使用 dict,何时使用元组列表?
    查看>>
    Python 3d 绘图 - 轴居中
    查看>>
    python ==》 字典
    查看>>
    python anaconda 安装使用
    查看>>
    python and或or 当参数传递的时候的用法
    查看>>
    Python append() 与列表上的 + 运算符,为什么这些会给出不同的结果?
    查看>>
    Python APP自动化测试工具adb与Monkey使用详解
    查看>>
    Python APP自动化测试框架Appium详解
    查看>>
    Python APP自动化测试框架开发实战
    查看>>
    python argparse模块
    查看>>
    Python asyncio库的学习和使用
    查看>>
    Python AttributeError:“dict“对象没有属性“append“
    查看>>
    Python base64和hashlib模块
    查看>>
    python basic programs
    查看>>
    python bert_gen.py 报错Unable to load weights from pytorch checkpoint file for......
    查看>>
    python binascii.Error: Incorrect padding
    查看>>