a606困難KMP 前綴函數與最長回文後綴

CPE:Extend to Palindromes (UVa 11475)

在線性時間內找出末尾需要補上的最少字元。

前往題目練習 →回報教學錯誤時間 O(n),空間 O(n)。

解題思路

若原字串 s 的最長回文後綴長度為 L,只需在末尾補上前 n−L 個字元的反轉。反過來,任何只補 k 個字元的回文,都要求原字串後 n−k 個字元自己為回文,所以最長回文後綴確實給出最少補字數。

令 r=reverse(s),建立 r+'#'+s 的 KMP 前綴函數。最後的前綴匹配長度就是 r 的前綴與 s 後綴的最大相同長度,也就是 L。# 不在英文字母輸入中,可阻止匹配越過分隔;每行讀至 EOF,不改變大小寫,答案為 s+r[L:]。

Step-by-step animation

示意:s=abac

回報動畫錯誤
步驟 1 / 3

反轉與串接

r=caba,計算 caba#abac 的前綴函數。

caba
#
abac
n
4

Reference solution

回報程式錯誤

完整程式

#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
    string s;
    while (getline(cin, s)) {
        if (!s.empty() && s.back() == '\r')
            s.pop_back();
        string r = s;
        reverse(r.begin(), r.end());
        string text = r + "#" + s;
        vector<int> pi(text.size());
        for (int i = 1; i < (int)text.size(); ++i) {
            int j = pi[i - 1];
            while (j && text[i] != text[j])
                j = pi[j - 1];
            if (text[i] == text[j])
                ++j;
            pi[i] = j;
        }
        cout << s << r.substr(pi.back()) << '\n';
    }
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多