#include <iostream>
#include <string>
using namespace std;
string preProvess(string s)
{
int n = s.size();
if (n == 0)
return "^$";
string ret = "^";
for (int i = 0; i < n; ++i)
ret += "#" + s.substr(i, 1);
ret += "#$";
return ret;
}
int longgest_palindrome(string s)
{
string T = preProvess(s);
int n = T.size();
int* p = new int[n];
int C = 0, R = 0;
for (int i = 1; i < n - 1; ++i)
{
int i_mirror = 2 * C - i;
p[i] = (R > i) ? min(R - i, p[i_mirror]) : 0;
while (T[i + 1 + p[i]] == T[i - 1 - p[i]])
p[i]++;
if (i + p[i] > R)
{
C = i;
R = i + p[i];
}
}
int max_len = 0;
int centerIndex = 0;
for (int i = 1; i < n - 1; ++i)
{
if (p[i] > max_len)
{
max_len = p[i];
centerIndex = i;
}
}
delete[] p;
return max_len;
}
int main()
{
string tmp;
cin >> tmp;
cout << longgest_palindrome(tmp) << endl;
return 0;
}
最长回文串manacher算法模板
最新推荐文章于 2021-04-06 11:55:08 发布