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

    你可能感兴趣的文章
    npm error Missing script: “server“npm errornpm error Did you mean this?npm error npm run serve
    查看>>
    npm error MSB3428: 未能加载 Visual C++ 组件“VCBuild.exe”。要解决此问题,1) 安装
    查看>>
    npm install CERT_HAS_EXPIRED解决方法
    查看>>
    npm install digital envelope routines::unsupported解决方法
    查看>>
    npm install 卡着不动的解决方法
    查看>>
    npm install 报错 EEXIST File exists 的解决方法
    查看>>
    npm install 报错 ERR_SOCKET_TIMEOUT 的解决方法
    查看>>
    npm install 报错 Failed to connect to github.com port 443 的解决方法
    查看>>
    npm install 报错 fatal: unable to connect to github.com 的解决方法
    查看>>
    npm install 报错 no such file or directory 的解决方法
    查看>>
    npm install 权限问题
    查看>>
    npm install报错,证书验证失败unable to get local issuer certificate
    查看>>
    npm install无法生成node_modules的解决方法
    查看>>
    npm install的--save和--save-dev使用说明
    查看>>
    npm node pm2相关问题
    查看>>
    npm run build 失败Compiler server unexpectedly exited with code: null and signal: SIGBUS
    查看>>
    npm run build报Cannot find module错误的解决方法
    查看>>
    npm run build部署到云服务器中的Nginx(图文配置)
    查看>>
    npm run dev 和npm dev、npm run start和npm start、npm run serve和npm serve等的区别
    查看>>
    npm run dev 报错PS ‘vite‘ 不是内部或外部命令,也不是可运行的程序或批处理文件。
    查看>>