这题子串不能出现在句中.
#include <stdio.h> #include <string.h> #define N 1000002 #define M 1000002 char a[M], b[N]; int Next[N]; void getNext(char s[], int len) { int i, j; i = 0; j = -1; Next[0] = -1; while (i < len) { if (j == -1 || s[i] == s[j]) ++i, ++j, Next[i] = j; else j = Next[j]; } } int KMP(const char a[], const char b[], int pos, int next[], int la, int lb) { int i, j; i = pos, j = 0; while (i < la) { if (j == -1 || a[i] == b[j]) ++i, ++j; else j = next[j]; if(j==lb&&i<la)// 因为不能在主串中间,所以主串没跑完,不能退出 { j=0; } } return j; } int main() { int numa,numb,lena,lenb; while (scanf("%s%s",a,b)!=EOF)// 注意下 之前打成NULL 一直OLE { lena=strlen(a); lenb=strlen(b); getNext(b , lenb); numb=KMP(a, b, 0,Next, lena,lenb); getNext(a , lena); numa=KMP(b, a, 0,Next, lenb,lena); if(numa>numb) { printf("%s%s\n",b,a+numa); } else if(numa<numb) { printf("%s%s\n",a,b+numb); } else //之前比较整合后 的字典序 没想到只用考虑 a,b原来的字符串的字典序 { if(strcmp(a,b)<=0) printf("%s%s\n",a,b+numb); else printf("%s%s\n",b,a+numa); } } return 0; }