-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Manacher's_Algorithm.cpp
95 lines (88 loc) · 1.73 KB
/
Manacher's_Algorithm.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include <bits/stdc++.h>
using namespace std;
/*
Manacher's Algorithm is used to the find all the pairs (i,j) such that substring s[i…j] is a palindrome.
*/
int main() {
string str;
cin>>str;
int n=str.size();
vector<int> d1(n), d2(n); //d1 - odd length palindrome, d2 - even length palindrome
for(int i=0, l=0, r=-1; i<n; ++i) {
int k;
if(i>r)
k=1;
else
k=min(d1[l+r-i],r-i+1);
while(0<=i-k && i+k<n && str[i-k]==str[i+k]){
k++;
}
d1[i]=k--;
if(i+k>r){
l=i-k;
r=i+k;
}
}
for(int i=0, l=0, r=-1; i<n; ++i){
int k;
if(i>r)
k=0;
else
k=min(d2[l+r-i+1],r-i+1);
while(0<=i-k-1&&i+k<n&&str[i-k-1]==str[i+k]){
k++;
}
d2[i]=k--;
if(i+k>r){
l=i-k-1;
r=i+k ;
}
}
int ans=0;
cout<<"Following are the pairs which are palindromes: \n";
for(int i=0; i<n; ++i){
int x=d1[i];
while(x){
ans=max(ans, 2*x-1);
cout<<i-x+1<<" "<<i+x-1<<"\n";
x--;
}
}
for(int i=0; i<n; ++i){
int x=d2[i];
while(x){
ans=max(ans, 2*x);
cout<<i-x<<" "<<i+x-1<<"\n";
x--;
}
}
cout<<"Length of longest palindromic substring: "<<ans;
return 0;
}
/*
Time Complexity: O(N)
Space Complexity: O(N)
INPUT
abcba
OUTPUT
Following are the pairs which are palindromes:
0 0
1 1
0 4
1 3
2 2
3 3
4 4
Length of longest palindromic substring: 5
INPUT
abba
OUTPUT
Following are the pairs which are palindromes:
0 0
1 1
2 2
3 3
0 3
1 2
Length of longest palindromic substring: 4
*/