procedure build_next; begin lena:=length(a);lenb:=length(b); next[0]:=lenb;next[1]:=lenb-1; for i:=1 to lenb-1 do if b[i]<>b[i+1] then begin next[1]:=i;break; end; k:=1; for i:=2 to lenb do begin p:=k+next[k]-1;L:=next[i-k]; if i+L<=p then next[i]:=L else begin j:=p-i+1; if j<0 then j:=0; while (i+j<lenb)and(a[i+j]=b[j]) do inc(j); next[i]:=j;k:=i; end; end; end; procedure build_ex; begin if lena<lenb then minlen:=lena else minlen:=lenb; ex[0]:=minlen; for i:=1 to minlen do if a[i]<>b[i] then begin ex[0]:=i;break; end; k:=0; for i:=1 to lena do begin p:=k+ex[k]-1;L:=next[i-k]; if i+L<=p then ex[i]:=L else begin j:=p-i+1; if j<0 then j:=0; while (i+j<lena)and(j<lenb)and(a[i+j]=b[j]) do inc(j); ex[i]:=j;k:=i; end; end; end;
原文:http://www.cnblogs.com/mjy0724/p/4381775.html