KMP应用http://acm.hdu.edu.cn/showproblem.php?pid=2594
riemann与marjorie拼接后riemannmarjorie前缀与后缀公共部分为 rie 长度为 3(即next[l] = next[14]的值,l为拼接后的长度)
但:aaaa与aa拼接后aaaaaa,next[l]不是结果,所以在aaaa和aa间加“#”,即aaaa#aa;
#include<stdio.h> #include<string.h> #include<math.h> #include<stdlib.h> #define N 50010 char s1[2 * N], s2[N]; int next[2 * N]; void GetNext(char s[]) { int k = -1, j = 0, l = strlen(s); next[0] = -1; while(j < l) { if(k == -1 || s[j] == s[k]) { k++; j++; next[j] = k; } else k = next[k]; } } int main() { int l1, l2, i, l; while(scanf("%s%s", s1, s2) != EOF) { l1 = strlen(s1); l2 = strlen(s2); s1[l1] = '#'; s1[l1 + 1] = '\0'; strcat(s1, s2); GetNext(s1); l = l1 + l2; if(next[l + 1] == 0) printf("0\n"); else { for(i = 0 ; i < next[l + 1] ; i++) printf("%c", s1[i]); printf(" %d\n", next[l + 1]); } } return 0; }