討論區
最長公共子序列
時間限制:3000 ms | 內存限制:65535 KB
難度:3
描述
咱們就不拐彎抹角了,如題,需要你做的就是寫一個程序,得出最長公共子序列。
tip:最長公共子序列也稱作最長公共子串(不要求連續),英文縮寫爲LCS(Longest Common Subsequence)。其定義是,一個序列 S ,如果分別是兩個或多個已知序列的子序列,且是所有符合此條件序列中最長的,則 S 稱爲已知序列的最長公共子序列。
輸入
第一行給出一個整數N(0
#include <stdio.h>
#include <string.h>
int main()
{
int i, j, n;
char str1[1001],str2[1001];
scanf("%d",&n);
while (n--)
{
int len1, len2;
scanf("%s",str1);
scanf("%s",str2);
len1 = strlen(str1);
len2 = strlen(str2);
int lcs[len1+1][len2+1];
memset(lcs, 0, sizeof(lcs)); // 二位數組初始化
for (i = 1; i <= len1; i++)
{
for (j = 1; j <= len2; j++)
{
if (str1[i-1] == str2[j-1])
lcs[i][j] = lcs[i-1][j-1] + 1;
else
// lcs[i][j] = max(lcs[i-1][j], lcs[i][j-1]);
lcs[i][j] = lcs[i-1][j] > lcs[i][j-1] ? lcs[i-1][j] :lcs[i][j-1];
}
}
printf("%d\n",lcs[len1][len2]);
}
return 0;
}