-
最长公共子序列(LCS)
-
Description
-
给定两个字符串 text1 和 text2,返回这两个字符串的最长 公共子序列 的长度。如果不存在 公共子序列 ,返回 0 。
-
一个字符串的 子序列 是指这样一个新的字符串:它是由原字符串在不改变字符的相对顺序的情况下删除某些字符(也可以不删除任何字符)后组成的新字符串。
-
例如,"ace" 是 "abcde" 的子序列,但 "aec" 不是 "abcde" 的子序列。两个字符串的 公共子序列 是这两个字符串所共同拥有的子序列。
-
-
Input
-
输入为两行每行一个字符串
-
-
Sample Input 1
abcde
ace
-
Sample Input 2
abbb
c
-
Output
-
输出最长公共子序列的长度
-
-
Sample Output 1
3
-
Sample Output 2
0
-
代码部分:
#include <stdio.h>
#include <string.h>
#define MaxNum 100
int dp[MaxNum][MaxNum];
char str1[MaxNum],str2[MaxNum];
int maxnum(int a,int b,int c){
if(a>=b && a>=c){
return a;
}
if(b>=a && b>=c){
return b;
}
if(c>=a && c>=b){
return c;
}
}
int LCS(int x,int y){
for(int i=0;i<=y;i++){
dp[i][0];
}
for(int j=0;j<=x;j++){
dp[0][j];
}
for(int i=1;i<=x;i++){
for(int j=1;j<=y;j++){
dp[i][j] = maxnum(dp[i-1][j],dp[i][j-1],dp[i-1][j-1]+(str1[i-1]==str2[j-1])); //字符串初始索引值为0,故减一
}
}
return dp[x][y];
}
main(){
fgets(str1,MaxNum, stdin);
fgets(str2,MaxNum, stdin);
str1[strcspn(str1,"\n")] = 0;
str2[strcspn(str2,"\n")] = 0;
int x = strlen(str1);
int y = strlen(str2);
printf("%d",LCS(x,y));
}
323

被折叠的 条评论
为什么被折叠?



