int manachar(){
int len = strlen(t);
s[0] = '&'; s[1] = '^';
for(int i = 1; i <= len; ++i)s[i << 1] = t[i - 1], s[i << 1 | 1] = '^';//在字符串中加入特殊字符
len ++; len <<= 1;//长度变为2
int ret = 0, mx = 0, id = 0;
//ret为最长回文串的长度,mx为回文串能够延伸到的最大长度,id为延伸到最大长度的回文串的中心位置
for(int i = 1; i < len; ++i){
if(mx > i)p[i] = min(p[id * 2 - 1], mx - i);
else p[i] = 1;
while(s[i - p[i]] == s[i + p[i]])p[i] ++;
if(mx < p[i] + i)mx = p[i] + i, id = i;
ret = max(ret, p[i]);
}
return ret - 1;
}
manachar 模板
最新推荐文章于 2021-05-27 19:46:25 发布