Manacher算法 线性时间求最大回文子串长度
原理性的东西在这里得到:http://www.open-open.com/lib/view/open1419150233417.html
/*Manacher算法*/ #include<iostream> #include<vector> #include<map> #include<stdio.h> #define maxn 100000 #define min(a,b) a>b?b:a #define max(a,b) a>b?a:b using namespace std; char str[maxn]; //元字符串 char tmp[2*maxn+1]; //转换后的字符串 int length; int len[2*maxn+1]; void Get_New() { int i,j; tmp[0]='@'; //字符串开头增加一个特殊字符,防止越界 for(i = 1;i <= 2*length;i += 2){ tmp[i] = '#'; tmp[i+1] = str[i/2]; } tmp[2*length+1]='#'; } int Manacher() { int i; int mid,maxlen,ans; len[0] = 1; mid = ans = maxlen = 0; for(i = 1;i <= 2*length+1;i ++){ if(maxlen > i){ len[i] = min(maxlen-i,len[2*mid-i]); } else{ len[i] = 1; } while(tmp[i-len[i]] == tmp[i+len[i]]) len[i] ++; printf("len[%d] = %d ",i,len[i]); printf("\n"); if(len[i] + i > maxlen){ maxlen = len[i] + i; mid = i; } ans = max(ans,len[i]); } return ans - 1; } int main(void) { int i,ans,pos; cin >>length; for(i = 0;i < length;i++) cin >> str[i]; Get_New(); ans = Manacher(); cout <<ans <<endl; return 0; }
posted on 2016-03-10 16:04 Tob's_the_top 阅读(221) 评论(0) 编辑 收藏 举报