最长回文字符串模板(manacher算法 时间复杂度O(n))
2017-05-08 15:21
375 查看
manacher算法详解:点击打开链接
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<iostream>
using namespace std;
const int N = 220005;
char str
;
int p
;
void manacher(char *s, int len)
{
p[0] = 1;
int mmax = 0, id = 0;
for(int i = 1; i< len; i++)
{
p[i] = mmax > i? min(p[id*2-i], mmax-i):1;
while(s[i+p[i]] == s[i-p[i]]) p[i]++;
if(i + p[i]> id + p[id])
{
id = i;
mmax = i+p[i];
}
}
}
int main()
{
while(~scanf("%s", str))
{
int len = strlen(str);
for(int i = len; i >= 0; i--)
{
str[(i<<1)+1] = '#';
printf("BUG1 %d\n", (i<<1)+1);
str[(i<<1)+2] = str[i];
printf("BUG2 %d\n", (i<<1)+2);
}
str[0] = '*';//防止数组越界
len = len*2+2;
printf("%s\n", str);
manacher(str, len);
int ans = 0;
for(int i = 0; i < len; i++)
ans = max(ans, p[i]-1);
printf("%d\n", ans);
}
return 0;
}
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<iostream>
using namespace std;
const int N = 220005;
char str
;
int p
;
void manacher(char *s, int len)
{
p[0] = 1;
int mmax = 0, id = 0;
for(int i = 1; i< len; i++)
{
p[i] = mmax > i? min(p[id*2-i], mmax-i):1;
while(s[i+p[i]] == s[i-p[i]]) p[i]++;
if(i + p[i]> id + p[id])
{
id = i;
mmax = i+p[i];
}
}
}
int main()
{
while(~scanf("%s", str))
{
int len = strlen(str);
for(int i = len; i >= 0; i--)
{
str[(i<<1)+1] = '#';
printf("BUG1 %d\n", (i<<1)+1);
str[(i<<1)+2] = str[i];
printf("BUG2 %d\n", (i<<1)+2);
}
str[0] = '*';//防止数组越界
len = len*2+2;
printf("%s\n", str);
manacher(str, len);
int ans = 0;
for(int i = 0; i < len; i++)
ans = max(ans, p[i]-1);
printf("%d\n", ans);
}
return 0;
}
相关文章推荐
- Manacher算法:求解最长回文字符串,时间复杂度为O(N)
- Manacher算法:求解最长回文字符串,时间复杂度为O(N)
- Manacher算法:求解最长回文字符串,时间复杂度为O(N)
- Manacher算法:求解最长回文字符串,时间复杂度为O(N)
- Manacher算法:求解最长回文字符串,时间复杂度为O(N)
- Manacher算法:求解最长回文字符串,时间复杂度为O(N)
- Manacher算法:求解最长回文字符串,时间复杂度为O(N)
- Manacher算法:求解最长回文字符串,时间复杂度为O(N)
- Manacher算法:求解最长回文字符串,时间复杂度为O(N)
- Manacher算法:求解最长回文字符串,时间复杂度为O(N)
- Manacher算法:求解最长回文字符串,时间复杂度为O(N)
- Manacher算法:求解最长回文字符串,时间复杂度为O(N)
- Manacher算法解决最长回文子串问题---O(n)时间复杂度
- Manacher算法O(n) 时间复杂度求最长回文字串及其长度
- 最长回文子串模板---Manacher算法。时间复杂度O(N)
- Manacher算法: O(n)时间求字符串的最长回文子串
- 求字符串的最长回文子串(manacher算法O(n)时间)
- Manacher算法: O(n)时间求字符串的最长回文子串
- 最长回文子串—动态规划和Manacher算法(0(n)时间复杂度
- hiho#1032 : 最长回文子串 (manacher算法O(n)时间求字符串的最长回文子串 )