← 回題庫

卷別

資料結構與演算法

申論

國立臺灣大學 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 P[1..m]P[1..m], the prefix function is π:{1,2,…,m}→{0,1,…,m−1}\pi:\{1,2,\dots,m\}\to\{0,1,\dots,m-1\} such that π[q]\pi[q] is the length of the longest prefix of PP that is a proper suffix of PqP_q (the qq-character prefix of PP). For pattern string P=P=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 π

標準解析

AI 已複查