问题描述:
在字母表∑上,分别给出长度为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;
}