LeetCode-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.
题目大意
给定一个字符串,可以在该字符串前加入任何字符,要求在经过若干操作之后,能使得该字符串成为回文串的最小长度的字符串,并返回该字符串。
示例
E1
E2
解题思路
思路来源于LeetCode@Sammax,将字符串的倒序和该字符串拼接在一起,并对该组合字符串进行KMP的next数组求解,可得到最终结果。
复杂度分析
时间复杂度:O(N)
空间复杂度:O(N)
代码
class Solution { public: string shortestPalindrome(string s) { string tmp = s; //求字符串的倒序 reverse(tmp.begin(), tmp.end()); //将正序与倒序进行拼接,中间应加入一个特殊字符,为了避免next数组计算时产生 //错误 string str = s + "#" + tmp; vector<int> next(str.length(), 0); //进行KMP算法,next数组计算 for(int i = 1, k = 0; i < str.length(); ++i) { while(k > 0 && str[i] != str[k]) k = next[k - 1]; if(str[i] == str[k]) ++k; next[i] = k; } return tmp.substr(0, tmp.size() - next[str.size() - 1]) + s; } };