LeetCode214. Shortest Palindrome(最短回文串)

214. Shortest Palindrome

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.

Example 1:

Input: "aacecaaa"
Output: "aaacecaaa"

Example 2:

Input: "abcd"
Output: "dcbabcd"

题目:给定一个字符串s,可以在s的前面添加字符使得s变为回文字符串,返回最短的回文字符串。

思路:参见分析。暴力的方法[Memory Limit Exceeded],首先找到从s首字符开始的最长的回文子串,然后将剩余的字符串反转后附加到s的前面,得到最短的回文串。

工程代码下载

class Solution {
public:
    string shortestPalindrome(string s) {
        string rev(s);
        reverse(rev.begin(), rev.end());
        int n = s.size();
        for(int i = 0; i < n; ++i){
            if(s.substr(0, n-i) == rev.substr(i))
                return rev.substr(0, i) + s;
        }
        return "";
    }
};

思路: KMP中求解next数组的思路,同样是为了找到从s首字符开始的最短的回文子串。next[i]表示字符串s的前i-1个字符构成的子串s[0...i-1]中,最长的相等的前缀和后缀。比如abaanext[3] = 1。KMP的理解可参见从头到尾彻底理解KMP。

string shortestPalindrome(string s)
{
    int n = s.size();
    string rev(s);
    reverse(rev.begin(), rev.end());
    string s_new = s + "#" + rev;
    int n_new = s_new.size();
    vector<int> f(n_new, 0);
    for (int i = 1; i < n_new; i++) {
        int t = f[i - 1];
        while (t > 0 && s_new[i] != s_new[t])
            t = f[t - 1];
        if (s_new[i] == s_new[t])
            ++t;
        f[i] = t;
    }
    return rev.substr(0, n - f[n_new - 1]) + s;
}

你可能感兴趣的:(leetcode)