题解 | #查找两个字符串a,b中的最长公共子串#
查找两个字符串a,b中的最长公共子串
https://www.nowcoder.com/practice/181a1a71c7574266ad07f9739f791506
#include <stdio.h> #include <string.h> int main() { char a[301], b[301]; while (scanf("%s\n%s", a, b) != EOF) { int maxLen = 0; int maxindex = 0; int lenA = strlen(a); int lenB = strlen(b); if (lenA > lenB) { char temp[301]; strcpy(temp, a); strcpy(a, b); strcpy(b, temp); int templen = lenA; lenA = lenB; lenB = templen; } for (int i = 0; i < lenA; i++) { for (int j = 0; j < lenB; j++) { if (a[i] == b[j]) { int tempmax = 0; int tempi = i; int tempj = j; while (tempi < lenA && tempj < lenB && a[tempi] == b[tempj]) { tempi++; tempj++; tempmax++; } if (tempmax > maxLen) { maxLen = tempmax; maxindex = i; } else if (tempmax == maxLen && i < maxindex) { maxindex = i; } } } } for ( int i = 0; i < maxLen; i++) { printf("%c", a[i + maxindex]); } printf("\n"); } return 0; }