Function: Enter a original string, then enter N to match the string, in the string to be matched to find out the starting position of all the original string
Principle: KMP algorithm, in fact, this thing already contains the idea of AC automata (fail pointer/array), but only applicable to single template matching, but it is worth mentioning that in a large number of single template matching string to be matched, this will have considerable advantages, AC automata Although good think some, But the price/performance ratio on this kind of problem is slightly lower.
1 var2 I,j,k,l,m,n:longint;3A:Array[0..100000] ofLongint;4 s1,s2:ansistring;5 begin6 readln (S1);7a[1]:=0;8 fori:=2 toLength (S1) Do9 beginTenj:=a[i-1]; One while(j>0) and(s1[j+1]<>s1[i]) Doj:=A[j]; A ifs1[j+1]=s1[i] Thena[i]:=j+1 Elsea[i]:=0; - End; - READLN (n); the forl:=1 toN Do - begin - readln (S2); -j:=0; + fori:=1 toLength (S2) Do - begin + Inc (J); A ifS1[j]=s2[i] Then at begin - ifJ=length (S1) Then - begin -Write (I-length (S1) +1,' '); -j:=A[j]; - End; in End - Else to begin +j:=j-1; - while(j>0) and(s1[j+1]<>s2[i]) Doj:=A[j]; the ifs1[j+1]=s2[i] ThenInc (J)Elsej:=0; * End; $ End;Panax Notoginseng Writeln; - End; the Readln; + End. A
Algorithm template--KMP string matching