您的位置:首页 > 其它

Manacher O(n) 回文字符串查找算法

2016-08-12 19:38 176 查看
虽然在题目中, 这类算法出现得比较少,

但其效率的确很好并且不是很难懂, 所以学一下也总有用得到的时候;

下面是一篇不错的博客, 推荐;

http://www.open-open.com/lib/view/open1419150233417.html

for(; s[i - len[i]] == s[i + len[i]]; len[i]++);


并说明一下, 有些读者认为这句话没有意义但实际上

我们设当前正匹配i位置, 找到的最远的地方max_dist(即当前找出的longest回文串所到达的地方)设中心点为id,max_dist 的对应点Min_dist,

i关于id对应的点是j, 所以我们用j来更新len【i】, 有的读者可能认为只要len【j】正确, 计算len【i】是不需要这句话的。

其实不然, 因为如果回文串的部分超过min_dist的话是无法保证超出的部分在id的另一侧是对称的, 所以这一句话相当有必要;

给出裸题

HDU 3068代码

#include <bits/stdc++.h>
using namespace std;

#define N 110005
#define rep(i, s, t) for(int i = s, end = t; i <= end; ++i)

struct Manacher{
int len, p[N<<1], res = -1;
char s[N<<1], str
;
void read() {
res = -1;
len = strlen(str);
s[0] = '$';
rep(i, 0, len - 1)
s[i<<1|1] = '#', s[(i+1)<<1] = str[i];
s[len<<1|1] = '#';
}

void match() {
int Max_dist = 0, id;
rep(i, 1, len<<1|1) {
if(Max_dist > i) p[i] = min(Max_dist - i, p[2*id-i]);
else p[i] = 1;
for(; s[i - p[i]] == s[i + p[i]]; p[i]++);
if(p[i] + i >Max_dist) Max_dist = p[i] + i, id = i;
}
}

int solve() {
read();

match();

rep(i, 1, len<<1|1)
res = max(res, p[i] - 1);
return res;
}
}M;

int main() {
#ifndef ONLINE_JUDGE
freopen("data.in", "r", stdin);
freopen("result.out", "w", stdout);
#endif
while(scanf("%s", M.str) != EOF){
printf("%d\n", M.solve());
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: