卷別
資料結構與演算法
申論國立臺灣大學 2023 · 考試 · 第 16 題
考科演算法
(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 is such that is the length of the longest prefix of that is a proper suffix of (the -character prefix of ). For pattern string ABACABACABACABAD, how many times is line 7 executed?
COMPUTE-PREFIX-FUNCTION(P)
1 m = P.length
2 let π[1..m] be a new array
3 π[1] = 0
4 k = 0
5 for q = 2 to m
6 while k > 0 and P[k+1] ≠ P[q]
7 k = π[k]
8 if P[k+1] == P[q]
9 k = k + 1
10 π[q] = k
11 return π