两个字符串的最长公共子串

例如str1:=“abcd”;str2 = “bcde”;

定义一个二维数组啊arr[4[4];



字符串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);

	
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值