/*主函数里初始化和调用*/ /*next[0] = 0; exkmp(s2+1,s2,next+1,next); exkmp(s1,s2,ex,next);*/ /*扩展kmp算法可以用o(n+m)的复杂度求出字符串s1的任意后缀与字符串s2的最长公共前缀*/ /*扩展kmp算法的next[i]==j表示s2的以s2[i]为起始的后缀与串本身的最长公共前缀长度*/ /*ex[i]为s1[i..]与s2的最长公共前缀,next[i]为s2[i..]与s2的最长公共前缀*/ void exkmp(char s1[],char s2[],int ex[],int next[]) { int i,j,p; i = j = 0; p = -1; while(s1[i]!=' ') { if( p == -1) { j = 0; do p++; while(s1[i+p] != ' '&&s1[i+p] == s2[j+p]); ex[i] = p; } else if(next[j] < p) ex[i] = next[j]; else if(next[j] > p) ex[i] = p; else { j = 0; while(s1[i+p] != ' '&&s1[i+p] == s2[j+p]) p++; ex[i] = p; } i++; j++; p--; } ex[i] = 0; return; }