Skip to content

Commit ab6fee3

Browse files
committed
Add Manacher's algorithm
1 parent 282c194 commit ab6fee3

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

manacher.cpp

+58
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
string getPaddedString(const string& s, string delim = "#") {
5+
string paddedString = "#";
6+
for (const char& c : s) {
7+
paddedString += c;
8+
paddedString += delim;
9+
}
10+
return paddedString;
11+
}
12+
13+
long getMaxPos(const vector<long>& span) {
14+
long maxlen = 1, pos = 1, n = span.size();
15+
for (long i = 2; i < n; i++) {
16+
if (span[i] > maxlen) {
17+
maxlen = span[i];
18+
pos = i;
19+
}
20+
}
21+
return pos;
22+
}
23+
24+
string getUnpaddedString(const string& s, const long& maxPos, const long& maxlen) {
25+
string ans;
26+
long start = maxPos - maxlen + 1, end = maxPos + maxlen - 1;
27+
for (long i = start; i <= end; i++) {
28+
if (s[i] != '#') ans += s[i];
29+
}
30+
return ans;
31+
}
32+
33+
string manacher(const string& s) {
34+
string str = getPaddedString(s);
35+
long n = str.length();
36+
vector<long> span(n,1);
37+
long c = 0, r = 0;
38+
for (long i = 1; i < n; i++) {
39+
if (i <= r and 2*c - i >= 0) {
40+
span[i] = min(r - i + 1, span[2*c - i]);
41+
}
42+
while (i - span[i] >= 0 and i + span[i] < n and str[i - span[i]] == str[i+span[i]]) span[i]++;
43+
if (i + span[i] - 1 > r) {
44+
c = i;
45+
r = i + span[i] - 1;
46+
}
47+
}
48+
long maxPos = getMaxPos(span);
49+
long maxlen = span[maxPos];
50+
return getUnpaddedString(str, maxPos, maxlen);
51+
}
52+
53+
int main() {
54+
string s;
55+
cin >> s;
56+
cout << manacher(s) << endl;
57+
return 0;
58+
}

0 commit comments

Comments
 (0)