題目沒有說明輸入一定是前一個字符串的後綴和後一個字符串匹配,所以需要進行兩次kmp匹配,然後得出最大的匹配數。
#include <stdio.h>
#include <string.h>
#define MAX 100005
char strA[MAX], strB[MAX];
int next[MAX];
void getNext(char* str, int* next) {
int len;
int j, k;
j = 0;
k = -1;
next[0] = k;
len = strlen(str) - 1;
while (j < len) {
if (k == -1 || str[k] == str[j]) {
++k, ++j;
if (str[k] == str[j]) {
next[j] = next[k];
} else {
next[j] = k;
}
} else {
k = next[k];
}
}
}
int kmp(char* strA, char* strB) {
int lenA, lenB;
int i, j;
i = j = 0;
lenA = strlen(strA);
lenB = strlen(strB);
getNext(strB, next);
if (lenA > lenB) {
i = lenA - lenB;
}
while (i < lenA) {
if (j == -1 || strA[i] == strB[j]) {
++j, ++i;
} else {
j = next[j];
}
}
return j;
}
int main() {
int numA, numB, num;
int lenA, lenB, len;
int i;
while (scanf("%s%s", strA, strB) != EOF) {
numA = kmp(strA, strB);
numB = kmp(strB, strA);
num = numA > numB ? numA : numB;
if (num == 0) {
if (strcmp(strA, strB) < 0) {
printf("%s%s\n", strA, strB);
} else {
printf("%s%s\n", strB, strA);
}
} else {
if (numA == num) {
printf("%s%s", strA, strB + num);
} else {
printf("%s%s", strB, strA + num);
}
printf("\n");
}
}
return 0;
}