建议大家学一学比较巧妙的KMP算法吧,很有意思。推荐个题目:POJ3167 Cow Patterns 题解我会发在本博里。
这个KMP就木有什么好说的了吧,大家找百度百科学一下就可以了~
CODE
Program KMP;//By_Thispoet
Const
maxn=1000005;
Var
st,s :Ansistring;//st is long and s is short
pre :Array[-1..maxn]of Longint;
i,k,p,q,ans,n :Longint;
BEGIN
readln(n);
while n>0 do
begin
readln(st);
readln(s);
pre[1]:=0;
for i:=2 to length(st) do
begin
k:=pre[i-1];
while (k<>0)and(st[k+1]<>st[i]) do k:=pre[k];
if st[k+1]<>st[i] then pre[i]:=0 else pre[i]:=k+1;
end;
p:=0;q:=0;ans:=0;
while q<length(s) do
begin
inc(q);
while (p<>0)and(st[p+1]<>s[q]) do p:=pre[p];
if st[p+1]=s[q] then inc(p);
if p=length(st) then
begin
inc(ans);
p:=pre[p];
end;
end;
writeln(ans);
dec(n);
end;
END.