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

    你可能感兴趣的文章
    MySQL中使用IN()查询到底走不走索引?
    查看>>
    Mysql中使用存储过程插入decimal和时间数据递增的模拟数据
    查看>>
    MySql中关于geometry类型的数据_空的时候如何插入处理_需用null_空字符串插入会报错_Cannot get geometry object from dat---MySql工作笔记003
    查看>>
    mysql中出现Incorrect DECIMAL value: '0' for column '' at row -1错误解决方案
    查看>>
    mysql中出现Unit mysql.service could not be found 的解决方法
    查看>>
    mysql中出现update-alternatives: 错误: 候选项路径 /etc/mysql/mysql.cnf 不存在 dpkg: 处理软件包 mysql-server-8.0的解决方法(全)
    查看>>
    Mysql中各类锁的机制图文详细解析(全)
    查看>>