题目解析:
AC代码:
#include<iostream>
using namespace std;
#include<string>
#include<vector>
#include<algorithm>
string MaxStr(string&s1,string& s2){
//让短的字符串放在前面
if(s1.size()>s1.size())
swap(s1,s2);
int len1=s1.size();
int len2=s2.size();
//创建二维数组
vector<vector<int>>vec(len1+1,vector<int>(len2+1,0));//全部初始化为0
int start=0,maxsize=0;
for(int i=1;i<=len1;++i){
for(int j=1;j<=len2;++j){
//判断s1[i-1]==s2[j-1]
if(s1[i-1]==s2[j-1]){//跟前一个一样 那就将该数组下标的值
vec[i][j]=vec[i-1][j-1]+1;
}
//更新maxsize
if(maxsize<vec[i][j]){
maxsize=vec[i][j];
start= i- maxsize;
}
}
}
return s1.substr(start,maxsize);//从start开始往后面提取maxsize个元素
}
int main()
{
string s1,s2;
while(cin>> s1>> s2){
string ans=MaxStr(s1,s2);
if(ans.size()>0) cout<<ans<<endl;
else cout<<"-1"<<endl;
}
return 0;
}
如有错误,多多指教!