Manacher算法:点击打开链接
题目地址:点击打开链接
C++代码:
//
// 1528.cpp
// 九度练习题
//
// Created by leizh007 on 15/7/13.
// Copyright (c) 2015年 leizh007. All rights reserved.
//
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string preProcess(string str) {
if (str.size()==0) {
return "^$";
}
string ans="^";
for (int i=0; i<str.size(); ++i) {
ans+="#"+str.substr(i,1);
}
ans+="#$";
return ans;
}
int main() {
string str;
while (cin>>str) {
string T=preProcess(str);
int n=(int)T.size();
int *P=new int[n];
int C=0,R=0;
for (int i=1; i<n-1; ++i) {
int iMirror=2*C-i;
P[i]=R>i?min(P[iMirror], R-i):0;
while (T[i+P[i]+1]==T[i-P[i]-1]) {
++P[i];
}
if (i+P[i]>R) {
C=i;
R=i+P[i];
}
}
int ans=0;
for (int i=1; i<n-1; ++i) {
ans=max(ans,P[i]);
}
cout<<ans<<endl;
}
return 0;
}