-
Notifications
You must be signed in to change notification settings - Fork 43
/
Manacher's_Algorithm
71 lines (52 loc) · 1.03 KB
/
Manacher's_Algorithm
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <bits/stdc++.h>
using namespace std;
string text;
void findLongestPalindromicString()
{
int N = text.length();
if(N == 0)
return;
N = 2*N + 1;
int L[N];
L[0] = 0;
L[1] = 1;
int C = 1;
int R = 2;
int i = 0;
int iMirror;
int maxLPSLength = 0;
int maxLPSCenterPosition = 0;
int start = -1;
int end = -1;
int diff = -1;
for (i = 2; i < N; i++)
{
iMirror = 2*C-i;
L[i] = 0;
diff = R - i;
if(diff > 0)
L[i] = min(L[iMirror], diff);
while (((i + L[i]) < N && (i - L[i]) > 0) && ( ((i + L[i] + 1) % 2 == 0) ||(text[(i + L[i] + 1)/2] == text[(i - L[i] - 1)/2] ))) {
L[i]++;
}
if(L[i] > maxLPSLength) {
maxLPSLength = L[i];
maxLPSCenterPosition = i;
}
if (i + L[i] > R) {
C = i;
R = i + L[i];
}
}
start = (maxLPSCenterPosition - maxLPSLength)/2;
end = start + maxLPSLength - 1;
cout << "Longest Palindrome substring of " << text << " is ";
for(i=start; i<=end; i++)
cout << text[i];
cout << "\n";
}
int main() {
cin >> text;
findLongestPalindromicString();
return 0;
}