博客
关于我
HDU 6208 The Dominator of Strings (字符串find函数暴力过)
阅读量:374 次
发布时间:2019-03-05

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

为了解决这个问题,我们需要找到一个字符串,使得其他所有给定的字符串都是它的子串。如果存在这样的字符串,我们需要返回它;否则,返回"No"。

方法思路

  • 问题分析:我们需要找到一个最长的字符串,这个字符串应该是其他所有字符串的子串。如果没有这样的字符串,返回"No"。最长字符串可能有多个,但只要其中一个满足条件即可。

  • 步骤

    • 读取所有字符串。
    • 找出所有最长的字符串。
    • 对于每个最长的字符串,检查其他所有字符串是否都是它的子串。
    • 如果找到满足条件的字符串,返回它;否则,返回"No"。
  • 优化:使用字符串操作和查找方法来高效地检查子串关系,避免直接使用低效的算法。

  • 解决代码

    #include 
    #include
    #include
    #include
    #include
    using namespace std;int main() { ios::sync_with_stdio(false); int t = 0; vector
    all_strs; string line; // 读取输入 for (; t < 1; ) { getline(line); istringstream iss(line); int n_i = 0; string s_i; if (iss >> n_i >> s_i) { all_strs.push_back(s_i); t++; } else { // 无法读取有效输入,假设题目中没有这种情况 // 可以处理错误情况,比如t++,继续读取下一个 t++; } } if (all_strs.empty()) { cout << "No" << endl; return; } // 找出最长的字符串 int max_len = 0; vector
    candidates; for (const string& s : all_strs) { if (s.length() > max_len) { max_len = s.length(); candidates.clear(); candidates.push_back(s); } else if (s.length() == max_len) { candidates.push_back(s); } } // 检查每个候选是否是其他所有字符串的子串 for (const string& s_candidate : candidates) { bool valid = true; for (const string& s : all_strs) { if (s.empty()) { continue; } size_t pos = s_candidate.find(s); if (pos == string::npos) { valid = false; break; } } if (valid) { cout << s_candidate << endl; return; } } // 没找到满足条件的字符串 cout << "No" << endl; return;}

    代码解释

  • 读取输入:使用getlineistringstream来读取输入,确保正确处理多个空格和换行符。
  • 找出最长字符串:遍历所有字符串,记录最长的字符串及其位置。
  • 检查子串:对于每个最长的字符串,检查其他所有字符串是否是它的子串。使用find方法来查找子串位置。
  • 输出结果:如果找到满足条件的字符串,输出它;否则,输出"No"。
  • 这种方法确保了在处理大量字符串时的效率,并且能够正确找到满足条件的字符串。

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

    你可能感兴趣的文章
    Orcale表被锁
    查看>>
    svn访问报错500
    查看>>
    sum(a.YYSR) over (partition by a.hy_dm) 不需要像group by那样需要分组函数。方便。
    查看>>
    ORCHARD 是什么?
    查看>>
    Struts2中使用Session的两种方法
    查看>>
    Stream API:filter、map和flatMap 的用法
    查看>>
    STM32工作笔记0032---编写跑马灯实验---寄存器版本
    查看>>
    Static--用法介绍
    查看>>
    ssm旅游信息管理系统的设计与实现bus56(程序+开题)
    查看>>
    order by rand()
    查看>>
    SSM(Spring+SpringMvc+Mybatis)整合开发笔记
    查看>>
    ViewHolder的改进写法
    查看>>
    Orderer节点启动报错解决方案:Not bootstrapping because of 3 existing channels
    查看>>
    org.apache.axis2.AxisFault: org.apache.axis2.databinding.ADBException: Unexpected subelement profile
    查看>>
    sql查询中 查询字段数据类型 int 与 String 出现问题
    查看>>
    org.apache.commons.beanutils.BasicDynaBean cannot be cast to ...
    查看>>
    org.apache.dubbo.common.serialize.SerializationException: com.alibaba.fastjson2.JSONException: not s
    查看>>
    sqlserver学习笔记(三)—— 为数据库添加新的用户
    查看>>
    org.apache.http.conn.HttpHostConnectException: Connection to refused
    查看>>
    org.apache.ibatis.binding.BindingException: Invalid bound statement错误一例
    查看>>