C语言实现字符串最大公串查找算法
你可以使用以下函数来实现:
#include <stdio.h>
#include <string.h>
char* findCommonString(char* str1, char* str2) {
int len1 = strlen(str1);
int len2 = strlen(str2);
int maxLen = 0;
int endIndex = 0;
int dp[len1+1][len2+1];
memset(dp, 0, sizeof(dp));
for (int i = 1; i <= len1; i++) {
for (int j = 1; j <= len2; j++) {
if (str1[i-1] == str2[j-1]) {
dp[i][j] = dp[i-1][j-1] + 1;
if (dp[i][j] > maxLen) {
maxLen = dp[i][j];
endIndex = i - 1;
}
}
else {
dp[i][j] = 0;
}
}
}
char* commonStr = (char*)malloc((maxLen+1) * sizeof(char));
strncpy(commonStr, str1 + endIndex - maxLen + 1, maxLen);
commonStr[maxLen] = '\0';
return commonStr;
}
int main() {
char str1[] = "adbccadebbca";
char str2[] = "edabccadece";
char* commonStr = findCommonString(str1, str2);
printf("最大公串为:%s\n", commonStr);
free(commonStr);
return 0;
}
这个函数使用动态规划的方法来找到两个字符串的最大公串。在二维数组dp中,dp[i][j]表示以str1[i-1]和str2[j-1]结尾的最大公串的长度。如果str1[i-1]和str2[j-1]相等,则dp[i][j] = dp[i-1][j-1] + 1,否则dp[i][j] = 0。在遍历的过程中,记录最大公串的长度maxLen和结束索引endIndex,然后根据endIndex和maxLen来提取最大公串。
原文地址: https://www.cveoy.top/t/topic/qEVw 著作权归作者所有。请勿转载和采集!