最长公共子序列问题——动态规划

问题描述:

在字母表∑上,分别给出长度为n和m的字符串A和B,确定在A和B中最长公共子序列的长度

样例输入:

“abc”

“ac”

样例输出:

2


说明:

最长公共子序列:如果字符串一的所有字符按其在字符串A中的顺序出现在另外一个字符串B中,则字符串一称为字符串B的子序列。

例如:A:“zxyxyz” 和 B :”xyyzx “,它们的最长公共子序列是xyyz


解决方案:

符合动态规划的思想:采用自底向上的方式递推求值,并把中间结果存储起来以便以后用来计算所需要的解。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define max(x,y) ((x) > (y) ? (x) : (y))

//get the length of the longest common subsequence from string A and string B
//Input:strA - string A
//      strB - string B
//Output:the length of the longest common subsequence
int GetLenOfLCS(char *strA, char *strB)
{
	if(!strA || !strB)
		return 0;

	int iLenOfA = strlen(strA);
	int iLenOfB = strlen(strB);

	int **arrLen;
    arrLen = (int **)malloc(sizeof(iLenOfA + 1));
	if(arrLen == NULL){
		fprintf(stderr,"allocate space error!\n");
		exit(EXIT_FAILURE);
	}
	for(int i = 0; i < iLenOfA + 1; i++){
		arrLen[i] = (int *)malloc(sizeof(iLenOfB + 1));
		if(arrLen[i] == NULL){
			fprintf(stderr,"allocate space error!\n");
			exit(EXIT_FAILURE);
		}
	}

	for(int i = 0; i <= iLenOfA; i++)
		arrLen[i][0] = 0;

	for(int j = 0; j <= iLenOfB; j++)
		arrLen[0][j] = 0;

	for(int i = 1; i <= iLenOfA; i++)
		for(int j = 1; j <= iLenOfB; j++)
			if(strA[i - 1] == strB[j - 1]) arrLen[i][j] = arrLen[i - 1][j - 1] + 1;
			else arrLen[i][j] = max(arrLen[i][j - 1], arrLen[i - 1][j]);

	return arrLen[iLenOfA][iLenOfB];
}

#define MAXSIZE 100

int main(void)
{
	char strA[MAXSIZE];
	char strB[MAXSIZE];

	fscanf(stdin,"%s",strA);
	fscanf(stdin,"%s",strB);
	printf("%d\n",GetLenOfLCS(strA,strB));
	return 0;
}




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值