例如str1:=“abcd”;str2 = “bcde”;
定义一个二维数组啊arr[4[4];
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLiQ3chVEa0V3bT9CX5RXa2Fmcn9CXwczLcVmds92czlGZvwVP9EUTDZ0aRJkSwk0LcxGbpZ2LcBDM08CXlpXazRnbvZ2LcRlMMVDT2EWNvwFdu9mZvwVPVNDZxQ2MaVnRXFWck1mYohmMZZXUYpVd1kmYr50MZV3YyI2cKJDT29GRjBjUIF2LcRHelR3LcJzLctmch1mclRXY39zN4YjMwQTM2ETNxkDMzEDMy8CX0Vmbu4GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)
字符串1,2若有相同的字符,对应的数组设置为一,对角线连续为1,对应的为公共子串,找出最长的即可。
void lSubstring(char *str1,char *str2,char *res)
{
int i = 0,j = 0;
int len1 = strlen(str1);
int len2 = strlen(str2);
int starti,startj,si,sj;
int max=0,len=0,savei,savej;
int **arr;
char *p = NULL;
char *tmp = (char*)malloc(sizeof(char)*256);
memset(tmp,'\0',256);
int pos[3];
arr = (int**)malloc(sizeof(int)*len1);
for(;i<len1;i++)
{
arr[i] = (int*)malloc(sizeof(int)*len2);
memset(arr[i],0,len2);
}
for(i = 0;i < len1;i++)
for(j = 0; j< len2;j++)
{
if(str1[i]==str2[j])
{
// printf("str1[%d]=%c,str2[%d]=%c\n",i,str1[i],j,str2[j]);
arr[i][j] = 1;
}
}
for(i = 0;i < len1;i++)
for(j = 0; j< len2;j++)
if(arr[i][j] == 1)
{
starti = i;
startj = j;
savei =i;
savej = j;
len++;
savei++,savej++;
// printf("%d,%d\n",i,j);
while(savei<len1 && savej<len2 && arr[savei][savej] ==1)
{
printf("%d,%d\n",savei,savej);
len++;
savei++;
savej++;
}
if(len>=max)
{
si = savei;
sj = savej;
max = len;
}
len = 0;
}
strncpy(res,&str1[si],max);
}