214. Shortest Palindrome
https://leetcode.com/problems/shortest-palindrome/description/
Thoughts
Code
/*
* @lc app=leetcode id=214 lang=cpp
*
* [214] Shortest Palindrome
*/
// @lc code=start
class Solution {
public:
string shortestPalindrome(string s) {
const auto next = [](string s) {
const int N = s.length();
vector<int> dp(N, 0);
for (int i = 1; i < N; ++i) {
int j = dp[i - 1];
while (j > 0 && s[i] != s[j]) {
j = dp[j - 1];
}
if (s[i] == s[j]) dp[i] = j + 1;
}
return dp;
};
auto rev_s = s;
reverse(rev_s.begin(), rev_s.end());
const auto next_vec = next(s + "#" + rev_s);
return rev_s.substr(0, s.size() - next_vec[next_vec.size() - 1]) + s;
}
};
// @lc code=end
Analysis
Last updated