求两个字符串最长公共子串(动态规划)

code如下:

//Longest common sequence, dynamic programming method

void FindLCS(char *str1, char *str2)
{
	if(str1 == NULL || str2 == NULL)
		return;
	int length1 = strlen(str1)+1;
	int length2 = strlen(str2)+1;
	int **csLength,**direction;//two arrays to record the length and direction
	int i,j,maxLength=0,maxI=0,maxJ=0;
	csLength = (int **)new int[length2];
	for(i=0; i<length1; i++)
		csLength[i] = (int *)new int[length1];
	for(i=0;i<length2;i++)
		for(j=0;j<length1;j++)
			csLength[i][j] = 0;
	direction = (int **)new int[length2];
	for(i=0; i<length1; i++)
		direction[i] = (int *)new int[length1];
	for(i=0;i<length2;i++)
		for(j=0;j<length1;j++)
			direction[i][j] = 0;
	for(i=1;i<length2;i++)
		for(j=1;j<length1;j++)
		{
			if(str2[i-1] == str1[j-1])
			{
				csLength[i][j] = csLength[i-1][j-1] + 1;
				direction[i][j] = 3;//3 means leftup
			}
			else if(csLength[i-1][j] > csLength[i][j-1])
			{
				csLength[i][j] = csLength[i-1][j];
				direction[i][j] = 1;//1 means left
			}				
			else
			{
				csLength[i][j] = csLength[i][j-1];
				direction[i][j] = 2;//2 means up
			}
			if(maxLength < csLength[i][j])
			{
				maxLength = csLength[i][j];//record th max length and the corresponding index
				maxI = i;
				maxJ = j;
			}
		}
	i = maxI;
	j = maxJ;
	//the output is in reverse order
	while(i!=0 && j!= 0)
	{
		if( str2[i-1] == str1[j-1])
			cout<<str2[i-1]<<" ";
		if(direction[i][j] == 3)
		{
			i--;
			j--;
		}
		else if(direction[i][j] == 1)
		{
			i--;
		}
		else if(direction[i][j] == 2)
		{
			j--;
		}
	}
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值