题解 | #查找两个字符串a,b中的最长公共子串#
查找两个字符串a,b中的最长公共子串
https://www.nowcoder.com/practice/181a1a71c7574266ad07f9739f791506
#include <stdio.h> #include <string.h> int main() { char stra[300], strb[300], out[300], buf[300] = { 0 }; int i, j, k = 0, cnt = 0, max = 0; scanf("%s", stra); scanf("%s", strb); if (strlen(stra) > strlen(strb)) { strcpy(buf, strb); strcpy(strb, stra); strcpy(stra, buf); }//保证短串一定是stra for (i = 0; i < strlen(stra); i++) { for (j = 0; j < strlen(strb); j++) { i = i - cnt; cnt = 0; k = 0; memset(buf, 0, 300); while (stra[i] == strb[j]) { buf[k] = stra[i]; cnt++; i++; k++; j++; } if (cnt > max) { max = cnt; strcpy(out, buf); j--; } } } printf("%s", out); return 0; }