我的公共子字符串查找方法,非递归实现或者可以说没有实现递归

参考文章地址如下:http://blog.csdn.net/hackbuteer1/article/details/6686931

子字符串的定义和子序列的定义类似,但要求是连续分布在其他字符串中。比如输入两个字符串BDCABA和ABCBDAB的最长公共字符串有BD和AB,它们的长度都是2。

Substring可以用动态规划解决,令    c[i][j]表示Xi和Yi的最大Substring的长度,比如

   X = <y, e, d, f>

   Y = <y, e, k, f>

   c[1][1] = 1

   c[2][2] = 2

   c[3][3] = 0

   c[4][4] = 1

   动态转移方程为:

   如果xi == yj, 则 c[i][j] = c[i-1][j-1]+1

   如果xi ! = yj,  那么c[i][j] = 0

代码如下:

#include <stdio.h>
#include <string.h>
int comm_str(char * str1, char * str2)
{
	int i, j, k, max, x, y;
	const int len1 = strlen(str1);
	const int len2 = strlen(str2);
	int c[len1][len2];
	for(i = 0; i < len1+1; i++)
		for(j = 0; j < len2+1; j++)
			c[i][j] = 0;
	max = -1;
	for(i = 1; i < len1; i++)
	{
		k = 0;
		for(j=1; j < len2; j++)
		{
			if(str1[i-1+k] == str2[j-1])
			{
				c[i+k][j]=c[i-1+k][j-1]+1;
				if(c[i+k][j]>max)
				{
					max=c[i+k][j]; x=i+k; y=j;
				}
				k++;
			}			
			else
				c[i+k][j]=0;
		}
	}

	char s[10000];
	k=max;
	i=x-1, j=y-1;
	s[k--]='\0';
	while(i>=0 && j>=0 && k >= 0)
	{
		if(str1[i]==str2[j])
		{
			s[k--]=str1[i]; i--; j--;
		}
		else
			break;
	
	}
	printf("most longest common str:");
	puts(s);
	
	return max;
}
int main()
{
	char str1[10000], str2[10000];
	puts("please input first string:");	gets(str1);
	puts("please input second string:");	gets(str2);	
	printf("the length of longest common substring is %d\n",comm_str(str1, str2));
}
执行结果如下:


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值