题解 | #查找两个字符串a,b中的最长公共子串#
查找两个字符串a,b中的最长公共子串
https://www.nowcoder.com/practice/181a1a71c7574266ad07f9739f791506
#include <stdio.h> #include <string.h> void printMaxSubLen(char* s,int slen, char* l,int llen) { char maxstr[300] = {0}; int maxstrlen = 0; int beginidx = 0, endidx = 0; int samecount = 0; char oldeqflag = 0; //0 不相等 ; 1相等 int findeqflag = 0; for(int i = 0; i < slen; i++) { beginidx = 0; samecount = 0; for(int j = 0; j < llen; j++) { beginidx = 0; samecount = 0; for(int k = j; k < llen; k++){ if(s[i+samecount] == l[k]) { if(0 == findeqflag) { beginidx = i; findeqflag = 1; } samecount++; } else //if(s[i+samecount] != l[k]) { if(1 == findeqflag) { findeqflag = 0; //check & save if(samecount > maxstrlen) { strncpy(maxstr, s + beginidx, samecount); maxstrlen = samecount; } } samecount = 0; findeqflag = 0; } } } } //print for(int i = 0; i < maxstrlen; i++) { printf("%c",maxstr[i]); } } int main() { char s[308] = {0}; int slen = 0; char l[308] = {0}; int llen = 0; scanf("%s",s); slen = strlen(s); scanf("%s",l); llen = strlen(l); if(slen <= llen) printMaxSubLen(s,slen, l,llen); else printMaxSubLen(l,llen,s,slen); return 0; }