[目前未找到题目]扩展KMP模板

procedure build_next;
begin
    lena:=length(a);lenb:=length(b);
    next[0]:=lenb;next[1]:=lenb-1;
    for i:=1 to lenb-2 do if b[i]<>b[i+1] then 
    begin
        next[1]:=i;break;
    end;
    k:=1;
    for i:=2 to lenb-1 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-1 do if a[i]<>b[i] then
    begin
        ex[0]:=i;break;
    end;
    k:=0;
    for i:=1 to lena-1 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;

 

posted @ 2015-03-31 19:07  mjy0724  阅读(232)  评论(0编辑  收藏  举报