两条序列比较,将短的和长的比,从短的尾部和长的头部开始比较,直到短序列的头部和长序列的尾部比较完毕,比较结束。
可知k-max+1为两个序列的连续开端,k为尾部
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
#define N 50000
using namespace std;
int longest_substring(char *s1,char *s2)
{
int i,len,len1,len2,k,s1_st,s2_st,count,max,j;
len1=strlen(s1);
len2=strlen(s2);
len=len1+len2;
max=0;
for(i=0; i<len; i++)
{
s1_st=s2_st=0;
if(i<len1)
s1_st=len1-i;
else
s2_st=i-len1;
count=0;
for(j=0; (s1_st+j<len1)&&(s2_st+j<len2); j++)
{
if(s1[s1_st+j]==s2[s2_st+j])
count++;
else
{
max=count>max?count:max;
count=0;
}
}
if(count>max)
{
max=count;
k=s1_st+j-1;//公共字串在str1中的下标起始位置为k-max+1,结束位置为k
}
}
/*char s[1001];
for(i=0; i<max; i++)
s[i]=s1[k-max+i];
s[i]='\0';
puts(s);*/
return max;
}
int main()
{
char s1[1001],s2[1001];
gets(s1);
gets(s2);
int ans=longest_substring(s1,s2);
printf("%d\n",ans);
return 0;
}