菜鸟就要老老实实重新学起:
回文串(Manacher算法)
Manacher算法: http://blog.youkuaiyun.com/xingyeyongheng/article/details/9310555
HDU3068 最长回文
http://acm.hdu.edu.cn/showproblem.php?pid=3068
题意:
求字符串中最长回文子串;
思路:
但这道题可以简单的遍历每一个字符然后向左右搜索找到所有回文串长度;O(N*N) 然而过了;或者用Manacher算法,构造一个数组p[ i ] 记录第i个字符为中心的回文串向右的长度,取最大值;
两点:
一、在每个字符之间加上‘#’,解决奇偶串问题,则单侧p[i]即为回文串长度+1;
二、从左向右计算p[ i ] 时,分两种情况:
1、有p[ j ] + j > i ;即该节点被某个回文串包含时,i节点构造的回文串长度p[i]就等于i节点关于j节点对称处p[j*2-i],与i节点到j节点回文串最右端的距离的最小值;
if(p[res]+res > i)
p[i] = min(p[2*res-i],p[res]+res-i);
2、未被包含时,初始化为1;
else
p[i] = 1;
然后再向两边扫,可以有效缩小时间复杂度;
code:
直接扫:
#define N 123456
int n,m;
char s[N];
int fast(char *p)
{
int ans = 1;
for (int i = 0; p[i]; ++i)
{
int s = i, e = i, t;
while (p[e + 1] == p[i]) ++e;//判断中间相同的个数,处理偶数问题
i = e;
while (p[s - 1] == p[e + 1] && s>0) --s, ++e;//往两边扫
if ((t = e - s + 1) > ans) ans = t;
}
return ans;
}
int main()
{
int i,j,k,kk,t,x,y;
while(scanf("%s",s)!=EOF)
{
n = strlen(s);
printf("%d\n",fast(s));
}
return 0;
}
Manacher算法:
#define N 123456
int n,m;
int flag,sum,ave,ans,res;
int p[N*2];
char s[N*2];
int main()
{
int i,j,k,kk,t,x,y;
while(scanf("%s",s)!=EOF)
{
n = strlen(s);
res=ans=0;
for(i=n;i>=0;i--)
{
s[i+i+2] = s[i];
s[i+i+1] = '#';
}
s[0] = '*';
for(i=2;i<2*n+1;i++)
{
if(p[res]+res > i)
p[i] = min(p[2*res-i],p[res]+res-i);
else
p[i] = 1;
while(s[i-p[i]] == s[i+p[i]])
p[i]++;
if(res+p[res]<i+p[i])res=i;
if(ans<p[i])ans=p[i];
}
printf("%d\n",ans-1);
}
return 0;
}