算法提高 最长公共子序列

问题描述
  给定两个字符串,寻找这两个字串之间的最长公共子序列。
输入格式
  输入两行,分别包含一个字符串,仅含有小写字母。
输出格式
  最长公共子序列的长度。
样例输入
abcdgh
aedfhb
样例输出
3
样例说明
  最长公共子序列为a,d,h。
数据规模和约定
  字串长度1~1000。

#include<stdio.h>
#include<string.h>
//char lsc[100];
//int k=0;
int count=0;
void LCSLength(int line,int row,char str1[],char str2[],int temp[][1005],int arr[][1005])
{
	int i,j;
	for(i=1;i<=line;i++)
		temp[i][0]=0;
	for(i=0;i<=row;i++)
		temp[0][row]=0;
	for(i=1;i<=line;i++)
	{
		for(j=1;j<=row;j++)
		{
			if(str1[i-1]==str2[j-1])
			{
				temp[i][j]=temp[i-1][j-1]+1;
				arr[i][j]=1;
			}
			else if(temp[i-1][j]>=temp[i][j-1])
			{
				temp[i][j]=temp[i-1][j];
				arr[i][j]=3;
			}
			else
			{
				temp[i][j]=temp[i][j-1];
				arr[i][j]=2;
			}
		}
	} 
}
int LCS(int line,int row,char str1[],int arr[][1005])
{
	if(line==0 || row==0)
		return 0;
	if(arr[line][row]==1)
	{
		count++;
//		lsc[k++]=str1[line-1];
		LCS(line-1,row-1,str1,arr);
	}
	else if(arr[line][row]==2)
	{
		LCS(line,row-1,str1,arr);
	}
	else
	{
		LCS(line-1,row,str1,arr);
	}
}
int main()
{
	char str1[1005],str2[1005];
	int temp[1005][1005],arr[1005][1005];		//temp存表格,arr存判断 
	int len1;
	int len2;
	scanf("%s%s",str1,str2);
	len1=strlen(str1);
	len2=strlen(str2);
	LCSLength(len1,len2,str1,str2,temp,arr);	//str1是行,str2是列 
	LCS(len1,len2,str1,arr);
/*	lsc[k]='\0';
	for(int i=k-1;i>=0;i--)
		putchar(lsc[i]);
	printf("\n");
*/	printf("%d\n",count);
	return 0;
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值