演算法›Ch6 KMP 字串比對
第 1 題/共 3 題
◀ AL 1/3
1. KMP、Prefix Function
#AL-06-001中KMPPrefix Function

(9 points) The pseudo code function to compute the prefix function in the Knuth-Morris-Pratt (KMP) string matching algorithm is given below. Given a pattern string P[1..m]P[1..m], the prefix function for this pattern PP is the function π:{1,2,…,m}→{0,1,…,m−1}\pi: \{1,2,\ldots,m\} \to \{0,1,\ldots,m-1\} such that π[q]\pi[q] is the length of the longest prefix of PP that is a proper suffix of PqP_q, where PqP_q denotes the qq-character prefix of the string PP. For pattern string P=P=ABACABACABACABAD, how many times is line 7 executed? (Note: only the final answer will be graded and only fully correct answer will be given points)

COMPUTE-PREFIX-FUNCTION(P) 1 m=P.lengthm = P.length 2 let π[1..m]\pi[1..m] be a new array 3 π[1]=0\pi[1] = 0 4 k=0k = 0 5 for q=2q = 2 to mm 6 while k>0k > 0 and P[k+1]≠P[q]P[k+1] \ne P[q] 7 k=π[k]k = \pi[k] 8 if P[k+1]==P[q]P[k+1] == P[q] 9 k=k+1k = k+1 10 π[q]=k\pi[q] = k 11 return π\pi

📄 台大112
跳轉到第題
▤完整推導請見《WH 資工筆記 · 演算法》Ch6 KMP 字串比對
本章題號 · 1–3 / 3