最长公共子序列c语言源代码
时间: 2023-10-26 16:13:42 浏览: 95
以下是最长公共子序列的C语言源代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int max(int a, int b) {
return (a > b) ? a : b;
}
int lcs(char* str1, char* str2, int len1, int len2) {
int** table = (int**)malloc((len1 + 1) * sizeof(int*));
for (int i = 0; i <= len1; i++) {
table[i] = (int*)malloc((len2 + 1) * sizeof(int));
}
for (int i = 0; i <= len1; i++) {
for (int j = 0; j <= len2; j++) {
if (i == 0 || j == 0) {
table[i][j] = 0;
}
else if (str1[i - 1] == str2[j - 1]) {
table[i][j] = table[i - 1][j - 1] + 1;
}
else {
table[i][j] = max(table[i - 1][j], table[i][j - 1]);
}
}
}
int result = table[len1][len2];
for (int i = 0; i <= len1; i++) {
free(table[i]);
}
free(table);
return result;
}
int main() {
char str1[100], str2[100];
printf("Enter first string: ");
scanf("%s", str1);
printf("Enter second string: ");
scanf("%s", str2);
int len1 = strlen(str1);
int len2 = strlen(str2);
int ans = lcs(str1, str2, len1, len2);
printf("Length of longest common subsequence: %d", ans);
return 0;
}
```
阅读全文