本文共 1588 字,大约阅读时间需要 5 分钟。
为了解决这个问题,我们需要找到一个字符串,使得其他所有给定的字符串都是它的子串。如果存在这样的字符串,我们需要返回它;否则,返回"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
方法来查找子串位置。这种方法确保了在处理大量字符串时的效率,并且能够正确找到满足条件的字符串。
转载地址:http://vrbwz.baihongyu.com/