给定两个字符串,例如 abceafg 和bcaedeafgabcea,求出它们两个最大的公有字符串,此题的解为最大长度是5,abcea。
代码如下:
#include<iostream>
#include<string>
using namespace std;
int main()
{
string str1, str2;
getline(cin, str1);
getline(cin, str2);
int maxL = 0, c = 0;
int t = 0;
for (int i = 0; i<str1.size()&&t<str1.size(); i++) {
auto re = str2.find(str1[i]);
while (re != string::npos) {
t = i;
int b = re;
while (t<str1.size() && re<str2.size() && str1[t] == str2[re]) {
++t;
++re;
}
if (maxL<t - i) {
c = i;
maxL = t - i;
}
if (b<str2.size() - 1) {
re = str2.find(str1[i],b+1);
}
else {
break;
}
if (t == str1.size()) {
break;
}
}
}
cout << maxL << endl;
cout << str1.substr(c, maxL) << endl;
return 0;
}