您的位置:首页 > 其它

求最长连续字串问题

2016-08-05 15:10 120 查看
注意这里讲的是连续,也就是substring,不是subsquence

我们有两个方法,动态规划和直尺法。

dp:建一个c[i][j]数组,表示在第i比较中,最长的连续长度

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#define N 500010
using namespace std;
int longest_substring(char *s1,char *s2)
{
int i,j,k,len1,len2,max,x,y;
len1=strlen(s1);
len2=strlen(s2);
int **c = new int*[len1+1];
for(i = 0; i < len1+1; i++)
c[i] = new int[len2+1];
for(i=0;i<len1+1;i++)
{
c[i][0]=0;
}
for(j=0;j<len2+1;j++)
c[0][j]=0;
max=-1;
for(i=1;i<len1+1;i++)
{
for(j=1;j<len2+1;j++)
{
if(s1[i-1]==s2[j-1])
{
c[i][j]=c[i-1][j-1]+1;
}
else
c[i][j]=0;
if(c[i][j]>max)
{
max=c[i][j];
x=i;
y=j;
}
}
}
char s[1000];
k=max;
i=x-1,j=y-1;
s[k--]='\0';
while(i>=0&&j>=0)
{
if(s1[i]==s2[j])
{
s[k--]=s1[i];
i--,j--;
}
else
break;
}
puts(s);
for(i=0;i<len1+1;i++)
delete[] c[i];
delete[] c;
return max;
}
int main()
{
char s1[1000],s2[1000];
gets(s1);
gets(s2);
int len=longest_substring(s1,s2);

printf("%d\n",len);
return 0;
}


直尺法:

#include <iostream>
#include  <cstdio>
#include <cstring>
#include <algorithm>
#define N 10010
/*直尺法:将短的一串从尾部开始进入和长的串头部比较,直到短的头部与长的尾部比较完毕
*/
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+1+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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: