KMP-MATCHER(T,P) 1 n ← length[T] 2 m ←length[P] 3 π ← COMPUTE-PREFIX-FUNCTION(P) 4 q ← 0 △Number of characters matched. 5 for i ← 1 to n △Scan the text from left to right. 6 do while q>0 and P[q+1]≠T[i] 7 doq ← π[q] △Next character does not match. 8 ifP[q+1]=T[i] 9 thenq ← q+1 △Next character matches. 10 ifq=m △Is all of P matched? 11 then print “Pattern occurs with shift” i-m 12 q ← π[q] △Look for the next match. COMPUTE-PERFIX-FUNCTION(P) 1 m ← length[P] 2 π[1] ← 0 3 k ← 0 4 forq ← 2 to m 5 do while k>0 and P[k+1]≠P[q] 6 dok ← π[k] 7 ifP[k+1]=P[q] 8 thenk ← k+1 9 π[q] ← k 10 return π[1]
模式匹配 串的最大匹配 算法 Algorithm on Maximal Matching of Strings Lin YuCai Xiang YongHong Zhang ChunXia Zhang JianJun (Computer Science Department of Yunnan Normal University Kunming 650092) ABSTRACT Given Two Strings S of length m and T of length n,the paper presents an algorithm which finds the maximal matching of them. The algorithm can be used to compare the similarility of the two strings S and T, it is different with the strings' pattren matching. KEY WORDS Pattern Matching Maximal Matching of Strings Algorithm
var next:array [1 ..1000001] of longint; s,t:ansistring; procedure get_next(t:ansistring); var j,k:integer; begin j:=1; k:=0; while j<length(t) do begin if (k=0) or (t[j]=t[k]) then begin inc(j); inc(k); next[j]:=k; end else k:=next[k]; end; end; function index(s:ansistring;t:ansistring):longint; var i,j:longint; begin get_next(t); index:=0; i:=1; j:=1; while (i<=length(s))and(j<=length(t)) do begin if (j=0)or(s[i]=t[j]) then begin inc(i); inc(j); end else j:=next[j]; if j>length(t) then index:=i-length(t); end; end; begin readln(s); readln(t); writeln(index(s,t)) end.