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"
分析
在字符串添加最少的字符得到回文数。暴力搜索的办法就是依次以每一个i为中点,查看左边的全部字符串的倒序可以在右边找到,然后再在前面补齐即可。但是这样应该会超时。
在字符串的前方添加字符组成回文串,其实就是需要找出该字符串中以0位开始已经组成的最大的回文串的长度。而回文串的特点是正序反序是相同的,可以计算s+'#' + rever(s)的next数组问题。next数组的定义就是求解前方出现的最长的重复序列长度。
Code
class Solution {
public:
string shortestPalindrome(string s) {
int length = s.size();
if (length == 0)
return "";
string s1 = s;
s1.push_back('#');
for (int i = length - 1; i >= 0; i --)
{
s1.push_back(s[i]);
}
vector<int> next(2*length + 2, 0);
next[0] = -1;
int j = 0;
int k = -1;
while (j < 2*length + 1)
{
if (k == -1 || s1[j] == s1[k])
{
next[++j] = ++k;
}
else
{
k = next[k];
}
}
string res = s;
int start = next[2*length + 1];
for (int i = start; i < length; i ++)
{
res.insert(0, 1, s[i]);
}
return res;
}
};
运行
Runtime: 272 ms, faster than 19.98% of C++ online submissions for Shortest Palindrome.
Memory Usage: 10.1 MB, less than 30.00% of C++ online submissions forShortest Palindrome.