典型的动态规划问题,非连续有点问题。
#include <stdlib.h>
#define N 100
int c[N];
int dp[N+5][N+5];
char* a="hijdefg";
char* b ="hfghijc";
int LCS(char* a, int aLen, char* b, int bLen){
int maxLen = 0;
int pos = 0;
int i = 0, j = 0;
for(; i < aLen; i++){
for(j = bLen; j >= 0; j--){
if(a[i] == b[j - 1]){
c[j] = c[j - 1] + 1;
if(c[j] > maxLen){
maxLen = c[j];
pos = j - 1;
}
}else{
c[j] = 0;
}
}
}
for(i = maxLen-1; i >= 0; i--){
printf("%c ",b[pos - i]);
}
return maxLen;
}
int NonContinousLCS(char* a, int aLen, char* b, int bLen){
int i = 1, j = 1;
for(; i < aLen; i++){
dp[i][0] = 0;
dp[0][i] = 0;
}
for(; i <= aLen; i++){
for(; j <= bLen; j++){
if(a[i - 1] == b[j - 1]){
dp[i][j] = dp[i-1][j-1] + 1;
}else{
dp[i][j] = max(dp[i-1][j],dp[i][j-1]);
}
}
}
return dp[aLen][bLen];
}
int max(int a, int b){
return a >= b ? a : b;
}
int main(){
LCS(a,8,b,8);
int result = NonContinousLCS(a,8,b,8);
printf("max len: %d",result);
getchar();
}