LeetCode 214. Shortest Palindrome

來源:互聯網
上載者:User
題目

Given a string S, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the shortest palindrome you can find by performing this transformation.

For example:

Given “aacecaaa”, return “aaacecaaa”.

Given “abcd”, return “dcbabcd”.
給你一個串。求最少在前面補多少個字母,能使其成為迴文串。 題解

網上基本做法就是構造一個串s+#+反轉(s),然後求新串的最長的和尾碼相等的首碼。
然後利用kmp裡面的next數組正好能求解。
其實這題還有個黑科技。。。
預先處理字串後,能在O(1)的時間裡比較兩子串是否相同。
連結:HASH求兩子串是否相等(O(N)預先處理O(1)比較)
所以就變成了很暴力的解法了。。 代碼

這裡只給出hash的解法,kmp的解法網上到處都是const int MAXN = 50100;const unsigned long long SEED = 13331;unsigned long long P[MAXN];unsigned long long S[MAXN];unsigned long long RS[MAXN];string ts;int n;unsigned long long HS(int l, int r) {//正向    if (l == r) {        return ts[l];    }    l++;    r++;    return S[r] - S[l - 1] * P[r - l + 1];}unsigned long long RHS(int l, int r) {//反向    if (l == r) {        return ts[l];    }    l = n - l - 1;    r = n - r - 1;    swap(l, r);    l++;    r++;    return RS[r] - RS[l - 1] * P[r - l + 1];}string shortestPalindrome(string s) {    ts = s;    P[0] = 1;    for (int i = 1; i < MAXN; i++) {        P[i] = P[i - 1] * SEED;    }    n = s.size();    for (int i = 1; i <= n; i++) {        S[i] = S[i - 1] * SEED + s[i - 1];    }    for (int i = 1; i <= n; i++) {        RS[i] = RS[i - 1] * SEED + s[n - i];    }    int ans = n - 1;    for (int i = 0; i < n / 2; i++) {        if (HS(0, i) == RHS(i + 1, i + 1 + i)) {            ans = min(ans, n - 2 * (i + 1 ));        }        if (2 * i + 2 < n && HS(0, i) == RHS(i + 2, i + 2 + i)) {            ans = min(ans, n - 2 * (i + 1) - 1);        }    }    string ss = "";    for (int i = 0; i < ans; i++) {        ss += s[n - i - 1];    }    ss += s;    return ss;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.