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

    代码解释

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

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

    你可能感兴趣的文章
    Python中执行外部命令
    查看>>
    Python中拼接numpy数组-ChatGPT4o作答
    查看>>
    Python中提示:no module named 'PIL'
    查看>>
    Python中提示:UnicodeDecodeError: 'ascii' codec can't decode byte 0xe5 in position
    查看>>
    python中数据类型存储_浅谈Python中的数据类型
    查看>>
    python中文件最重要的功能是什么-学 Python 都用来干嘛的?
    查看>>
    python中文版语言_高盛最新调查:Python超过汉语成为未来最重要技能,你准备学哪种编程语言?...
    查看>>
    Python中文问题SyntaxError
    查看>>
    Python中方括号和括号括起来的列表有什么区别?
    查看>>
    python中时间处理_Python中处理时间的几种方法小结
    查看>>
    Python中枚举串口(包括虚拟端口)的跨平台方法是什么?
    查看>>
    python中根号下a怎么写_python中根号怎么表示
    查看>>
    Python中正则表达式的巧妙使用
    查看>>
    Python中浮点数的二进制表示(位不是十六进制)
    查看>>
    Python中特殊函数和表达式 filter,map,reduce,lambda
    查看>>
    python中用socket检测端口_Python 用socket模块实现检测端口和检测web服务
    查看>>
    python中用于列表操作的plus和append有什么区别?
    查看>>
    python中用递归求和
    查看>>
    python中的@staticmethod
    查看>>
    python中的array函数作用_NumPy 数组使用大全
    查看>>