#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
/*
Given a string S, you are allowed to convert it to a palindrome by adding
characters in from 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"
*/
string shortestPalindrome(string s) {
string t = s;
reverse(t.begin(), t.end());
string tmp = t + '#' + s;
int n = tmp.size();
vector<int> dp(n, 0);
for(int i = 1; i <= tmp.size(); ++i) { // KMP algorithm
int j = dp[i-1];
while(j > 0 && (tmp[i] != tmp[j])) {
j = dp[j-1];
}
dp[i] = (j + (tmp[i] == tmp[j]));
}
return t.substr(0, s.size() - dp[tmp.size() - 1]) + s;
}
int main(void) {
cout << shortestPalindrome("abc") << endl;
}
LeetCode 214. Shortest Palindrome
最新推荐文章于 2022-11-01 19:17:22 发布
本文介绍了如何通过在字符串后添加字符使其成为回文串,并返回最短的回文串。详细步骤包括字符串反转、构建临时字符串、使用KMP算法找到最长前缀匹配并计算所需添加的字符数。

1096

被折叠的 条评论
为什么被折叠?



