Manacher O(n) 回文字符串查找算法
2016-08-12 19:38
176 查看
虽然在题目中, 这类算法出现得比较少,
但其效率的确很好并且不是很难懂, 所以学一下也总有用得到的时候;
下面是一篇不错的博客, 推荐;
http://www.open-open.com/lib/view/open1419150233417.html
并说明一下, 有些读者认为这句话没有意义但实际上
我们设当前正匹配i位置, 找到的最远的地方max_dist(即当前找出的longest回文串所到达的地方)设中心点为id,max_dist 的对应点Min_dist,
i关于id对应的点是j, 所以我们用j来更新len【i】, 有的读者可能认为只要len【j】正确, 计算len【i】是不需要这句话的。
其实不然, 因为如果回文串的部分超过min_dist的话是无法保证超出的部分在id的另一侧是对称的, 所以这一句话相当有必要;
给出裸题
HDU 3068代码
但其效率的确很好并且不是很难懂, 所以学一下也总有用得到的时候;
下面是一篇不错的博客, 推荐;
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; }
相关文章推荐
- SPOJ STC02 - Antisymmetry [Manacher]【思维】
- hdu 3068 最长回文 -Manacher
- PHP数组的查找算法
- Manacher 模板 【bzoj2565】 最长双回文子串
- 【 HDU3294 】Girls' research (Manacher)
- Manacher算法,回文串及后缀数组问题
- hdu3613 Best Reward manacher+贪心+前缀和
- 七大查找算法
- 查找算法:二分查找算法
- Manacher算法求最长回文子串
- 【查找算法】之折半查找
- [BZOJ3160]万径人踪灭(FFT+manacher)
- 数据结构之常见查找算法
- 查找算法
- 51Nod 1092 回文字符串
- HDU 3068 Manacher 算法 求最大回文
- KMP- Knuth-Morris-Pratt 字符串查找算法
- 最长回文串 Manacher
- 各种查找算法-Java-顺序、二分、二叉排序树查找
- hdu3068 最长回文(manacher)