最长连续公共子串算法

来源:互联网 发布:黑人ins视频软件 编辑:程序博客网 时间:2024/06/05 20:29
#include <stdio.h>/************************************************************************ 功能:     获取两个字符串的最长公共子串 描述:     时间复杂度跟两个字符串的长度有关,分别设为L1,L2,则时间复杂度为O(L1*L2) 参数:     lhs--字符串1 rhs--字符串2 返回值:     lhs和rhs两个字符串的最长公共子串的长度 ************************************************************************/int GetLCS(char *lhs, char *rhs){int lhsLen = strlen(lhs);int rhsLen = strlen(rhs);int i, j;int maxLength = 0;  // 记录最长公共子串的长度int count = 0;      // 累加计算子串的长度int startIndex = 0; // 记录最长公共子串的起始位置    int start1, start2; // 分别标记匹配公共子串的起点char *maxSubstring = NULL;for (i = 0; i < lhsLen; i++){for (j = 0; j < rhsLen; j++){start1 = i;start2 = j;// 查找公共子串while (start1 < lhsLen && start2 < rhsLen && lhs[start1] == rhs[start2]){count++;start1++;start2++;}if (count > maxLength){maxLength = count;startIndex = i;}count = 0;}} // 返回最长公共子串//maxSubstring = (char *)malloc(sizeof(char) * (maxLength + 1));//memset(maxSubstring, 0x00, maxLength + 1);    //memcpy(maxSubstring, lhs + startIndex, maxLength);//maxSubstring[maxLength] = '\0';//return maxSubstring;return maxLength;}int main(){char lhs[1000], rhs[1000];int len;int count;scanf("%d", &count);while (count--){scanf("%s%s", lhs, rhs);printf("%d\n", GetLCS(lhs, rhs));}return 0;}

原创粉丝点击