KMP
来源:互联网 发布:北京阿里云招聘 编辑:程序博客网 时间:2024/04/30 16:59
var
p:array[1..100000] of longint;
s1,s2:ansistring;
i,j:longint;
begin
readln(s1);
readln(s2);
p[1]:=0;
j:=0;
for i:=2 to length(s2) do
begin
while (j>0)and(s2[j+1]<>s2[i]) do j:=p[j];
if s2[j+1]=s2[i] then inc(j);
p[i]:=j;
end;
j:=0;
for i:=1 to length(s1) do
begin
while (j>0)and(s2[j+1]<>s1[i])do j:=p[j];
if s2[j+1]=s1[i] then inc(j);
if j=length(s2) then
begin
writeln(i-length(s2),' ');
j:=p[j];
end;
end;
end.
p:array[1..100000] of longint;
s1,s2:ansistring;
i,j:longint;
begin
readln(s1);
readln(s2);
p[1]:=0;
j:=0;
for i:=2 to length(s2) do
begin
while (j>0)and(s2[j+1]<>s2[i]) do j:=p[j];
if s2[j+1]=s2[i] then inc(j);
p[i]:=j;
end;
j:=0;
for i:=1 to length(s1) do
begin
while (j>0)and(s2[j+1]<>s1[i])do j:=p[j];
if s2[j+1]=s1[i] then inc(j);
if j=length(s2) then
begin
writeln(i-length(s2),' ');
j:=p[j];
end;
end;
end.
0 0