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".
Credits:
Special thanks to @ifanchu for adding this problem and creating all test cases. Thanks to @Freezen for additional test cases.
這道題讓我們求最短的迴文串,LeetCode中關於迴文串的其他的題目有 Palindrome Number 驗證迴文數字,Validate Palindrome 驗證迴文字串, Palindrome Partitioning 拆分迴文串,Palindrome Partitioning II 拆分迴文串之二和 Longest Palindromic Substring 最長迴文串。題目讓我們在給定字串s的前面加上最少個字元,使之變成迴文串,那麼我們來看題目中給的兩個例子,最壞的情況下是s中沒有相同的字元,那麼最小需要添加字元的個數為s.size() - 1個,第一個例子的字串包含一個迴文串,只需再在前面添加一個字元即可,還有一點需要注意的是,前面添加的字串都是從s的末尾開始,一位一位往前添加的,那麼我們只需要知道從s末尾開始需要添加到前面的個數。這道題如果用brute force無法通過OJ,所以我們需要用一些比較巧妙的方法來解。這裡我們用到了KMP演算法,KMP演算法是一種專門用來匹配字串的高效的演算法,具體方法可以參見這篇博文從頭到尾徹底理解KMP。我們把s和其轉置r串連起來,中間加上一個其他字元,形成一個新的字串t,我們還需要一個和t長度相同的一位元組p,其中p[i]表示從t[i]到開頭的子串的相同首碼尾碼的個數,具體可參考KMP演算法中解釋。最後我們把不相同的個數對應的字串添加到s之前即可,代碼如下:
class Solution {public: string shortestPalindrome(string s) { string r = s; reverse(r.begin(), r.end()); string t = s + "#" + r; vector<int> p(t.size(), 0); for (int i = 1; i < t.size(); ++i) { int j = p[i - 1]; while (j > 0 && t[i] != t[j]) j = p[j - 1]; p[i] = (j += t[i] == t[j]); } return r.substr(0, s.size() - p[t.size() - 1]) + s; }};
參考資料:
https://leetcode.com/discuss/36807/c-8-ms-kmp-based-o-n-time-%26-o-n-memory-solution
http://blog.csdn.net/v_july_v/article/details/7041827
http://www.cnblogs.com/easonliu/p/4522724.html