OR129. 最长公共子串
描述
有两个字符串(可能包含空格),请找出其中最长的公共连续子串,输出其长度。
输入描述
给定两行字符串输出描述
输出这两个字符串的最长公共连续子串的长度示例1
输入:
abcde bcd
输出:
3
C 解法, 执行用时: 2ms, 内存消耗: 316KB, 提交时间: 2021-09-09
#include <stdio.h> int LCS(char* str1, char* str2 ) { int len1=strlen(str1),len2=strlen(str2),i,j,k,mark,markmax,len=0,max=0; char a[1010]; for(i=0;i<len1;i++) { for(j=0;j<len2;j++) { len=1; if(str2[j]==str1[i]) { k=1; while(j+k<len2 && i+k<len1 && str2[j+k]==str1[i+k]) { len++; if(max<len) { max=len; } k++; } } } } return max; } int main() { char s[1010],t[1010]; while(scanf("%s %s",s,t)!=EOF) { printf("%d\n",LCS(s,t)); } return 0; }
C 解法, 执行用时: 2ms, 内存消耗: 328KB, 提交时间: 2021-08-24
#include<stdio.h> #include<string.h> int main() { char a[1000]; while (gets(a)) { char b[1000]; int i,j,i_,j_,len,max=0; gets(b); for(i=0;i<strlen(a);i++) { for(j=0;j<strlen(b);j++) { len=0; if(a[i]==b[j]) { i_=i; j_=j; while (a[i_]==b[j_]) { i_++; j_++; len++; } if(len>max) max=len; } } } printf("%d\n",max); } return 0; }