复杂度 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.
本文详细解析了复杂度为O(n)的算法原理,并通过实例展示了其在实际编程中的应用,包括字符串匹配算法的过程和优化技巧。
1万+

被折叠的 条评论
为什么被折叠?



