Consider a string of length , e.g., cbaabcba. We want to add the smallest number of characters to the front of the string to make it a palindrome, e.g., abcbaabcba. This problem can be solved by first concatenating the string with its inverse with a delimiter #, e.g. cbaabcba#abcbaabc. Then, run the pre-processing routine of the Knuth-Morris-Pratt algorithm on the new string of length to get a failure function , which computes the length of the longest prefix of the string that is also a suffix. After running the pre-processing routine, how can we calculate the smallest number of characters that should be added to the front of the original string to make it a palindrome?
參考答案與解析
答案 (E)。
在前面補最少的字元使字串成為回文,等於找原字串 的最長回文前綴,長度記為 ,答案是 。
組合字串 。 的某個前綴是回文,等價於它等於 的同長度後綴。中間有 隔開,所以 (整個 的最長相同前後綴)恰好是「 的前綴同時是 的後綴」的最長長度,也就是 。正確的公式是 。
- (D) 錯:對 取最大值,會把 中間任意位置與 的前綴對上的長度也算進去,這些長度不代表回文前綴。反例:(),最長回文前綴是 aa(),正確答案是補 6 個字元;但 的前三個字元 aab 與 的前綴 aab 相同, 在該位置等於 3,(D) 算出 。題目的例子 cbaabcba 剛好用 (D) 也得到 2,但不是每個字串都成立。
- (A)(C) 錯:只看 自身的失敗函數,與 無關。
- (B) 錯: 是 所在位置,值一定是 0,算出來永遠是 。
五個選項中沒有正確的公式,選 (E)。