-
Notifications
You must be signed in to change notification settings - Fork 0
/
leet214.cpp
51 lines (36 loc) · 857 Bytes
/
leet214.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Solution{
public:
string shortestPalindrome(string s)
{
int n = s.size();
string rev(s);
reverse(rev.begin(), rev.end());
string s_new = s + "#" + rev;
int n_new = s_new.size();
vector<int> f(n_new, 0);
for (int i = 1; i < n_new; i++) {
int t = f[i - 1];
while (t > 0 && s_new[i] != s_new[t])
t = f[t - 1];
if (s_new[i] == s_new[t])
++t;
f[i] = t;
cout << f[i] << endl;
}
return rev + s.substr(f[n_new - 1]);
//return rev.substr(0, n - f[n_new - 1]) + s;
}
};
int main(){
string s = "abbaa";
Solution sol;
string res = sol.shortestPalindrome(s);
for (int i=0; i<res.size(); ++i){
cout << res[i];
}
cout << endl;
}