编辑代码

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

#define MAX_LENGTH 100  

int max(int a, int b) {  
    return a > b ? a : b;  
}
  
char* longestCommonSubsequence(char *str1, char *str2) {  
    int len1 = strlen(str1);  
    int len2 = strlen(str2);  
    int dp[len1 + 1][len2 + 1];  
    int i, j;  
    for (i = 0; i <= len1; i++) {  
        for (j = 0; j <= len2; j++) {  
            if (i == 0 || j == 0) {  
                dp[i][j] = 0;  
            } else if (str1[i - 1] == str2[j - 1]) {  
                dp[i][j] = dp[i - 1][j - 1] + 1;  
            } else {  
                dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);  
            }  
        }  
    }  
    char *lcs = (char *)malloc((dp[len1][len2] + 1) * sizeof(char));  
    int index = dp[len1][len2];  
    for (i = len1; i >= 0; i--) {  
        if (dp[i][len2] == index) {  
            lcs[index - 1] = str1[i - 1];  
            index--;  
        }  
    }  
    lcs[dp[len1][len2]] = '\0';  
    return lcs;  
}  
  
int main() {  
    char str1[MAX_LENGTH], str2[MAX_LENGTH];  
    printf("Please enter the first string: ");  
    scanf("%s", str1);  
    printf("Please enter the second string: ");  
    scanf("%s", str2);  
    char *lcs = longestCommonSubsequence(str1, str2);  
    printf("The longest common subsequence is: %s\n", lcs);
    return 0;  
}