字符串处理基础算法-KMP

复杂度 O(n)

program pro;
var
        p:array[0..100]of longint;
        po:array[0..100]of longint;
        ans,l1,l2,i,j,k:longint;
        s1,s2:ansistring;

begin
        readln(s1);
        readln(s2);
        l1:=length(s1);
        l2:=length(s2);

        p[1]:=0; j:=0;//预处理:找出p数组
        for i:= 2 to l2 do
        begin
                while (j>0)and(s2[i]<>s2[j+1]) do j:=p[j];
                if s2[i]=s2[j+1] then inc(j);
                p[i]:=j;
        end;

        ans:=0;//寻找相同
        j:=0;
        for i:=1 to l1 do
        begin
                while (j>0)and(s1[i]<>s2[j+1]) do j:=p[j];
                if s1[i]=s2[j+1] then inc(j);
                if j=l2 then
                begin
                        inc(ans);
                        po[ans]:=i-l2+1;
                        j:=p[j];
                end;
        end;

        writeln(ans);
        for i:=1 to ans do writeln(po[i]);
end.

    原文作者:KMP算法
    原文地址: https://blog.csdn.net/free__radical/article/details/39967449
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞