解题思路:
(1)动态规划,注意为0的情况
#include<iostream>
#include<vector>
using namespace std;
string helper(string s1,string s2) {
if(s1.length()>s2.length()) {
string temp=s1;
s1=s2;
s2=temp;
}
int m = s1.length(),n=s2.length();
int maxlen=0,last=0;
vector<vector<int>> v(m+1,vector<int>(n+1,0));
for(int i=0;i<m+1;i++) {
for(int j=0;j<n+1;j++) {
if(i==0 || j==0) v[i][j]=0;
else if(s1[i-1]==s2[j-1]) {
v[i][j]=v[i-1][j-1]+1;
if(v[i][j]>maxlen) {
maxlen=v[i][j];
last=i;
}
} else v[i][j]=0;
}
}
return s1.substr(last-maxlen,maxlen);
}
int main() {
string s1,s2;
while(cin>>s1>>s2) {
cout<<helper(s1,s2)<<endl;
}
return 0;
}