[LeetCode] Shortest Palindrome

214. Shortest Palindrome

You are given a string s. You can convert s to a palindrome by adding characters in front of it.

Return the shortest palindrome you can find by performing this transformation.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
int lastMatch(string& s) {
vector<int> pi(s.length());
for(int i = 1, j = 0; i < s.length(); i++) {
while(j > 0 and s[i] != s[j])
j = pi[j-1];
if(s[i] == s[j]) {
pi[i] = ++j;
}
}
return pi.back();
}

public:
string shortestPalindrome(string s) {
string tmp = s;
reverse(tmp.begin(), tmp.end());
tmp = s + '#' + tmp;
int pos = lastMatch(tmp);
string rev = s.substr(pos);
reverse(rev.begin(), rev.end());
return rev + s;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/18/PS/LeetCode/shortest-palindrome/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.