(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 , the prefix function for this pattern is the function such that is the length of the longest prefix of that is a proper suffix of , where denotes the -character prefix of the string . For pattern string 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 2 let be a new array 3 4 5 for to 6 while and 7 8 if 9 10 11 return
參考答案與解析
答案:5 次。手動模擬 COMPUTE-PREFIX-FUNCTION:前 15 個字元 A,B,A,C,A,B,A,C,A,B,A,C,A,B,A 的 π 值一路順利遞增到 π[15]=11(因為 P 前 15 字元剛好是 ABACABACABACABA 的自我重複結構),中途只在 q=4(P[4]='C' 對 P[k+1]='B' 不符)觸發 1 次 line 7。到 q=16(P[16]='D')時,k 從 11 開始,因為 D 不等於 P[k+1],連續觸發 line 7:11→7→3→1→0,共 4 次,最後仍不相符,π[16]=0。加總:1(q=4)+4(q=16)=5 次。