palindrome 回文 /// Manacher算法

判断最长不连续回文

#include <bits/stdc++.h>
using namespace std;
int main()
{
char ch[];
while(gets(ch))
{
int len=strlen(ch),dp[],ans=;
for(int i=;i<len;i++)
ch[i]=tolower(ch[i]),dp[i]=;
for(int i=;i<len;i++)
{
int cnt=;
for(int j=i-;j>=;j--)
{
int tmp=dp[j];
if(ch[i]==ch[j]) dp[j]=cnt+;
cnt=max(cnt,tmp);
}
}
for(int i=;i<len;i++) ans=max(ans,dp[i]);
printf("%d\n",ans);
} return ;
}

过程如图

b b a c b b b c a d
1 1 1 1 1 1 1 1 1 1
2 1 1 1 1 1 1 1 1 1
2 1 1 1 1 1 1 1 1 1
2 1 1 1 1 1 1 1 1 1
3 3 1 1 1 1 1 1 1 1
5 3 1 1 2 1 1 1 1 1
5 4 1 1 3 2 1 1 1 1
5 4 1 5 3 2 1 1 1 1
5 4 7 5 3 2 1 1 1 1
5 4 7 5 3 2 1 1 1 1

判断最长连续回文

https://segmentfault.com/a/1190000008484167

Manacher模板

#include<ctype.h>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
char s[],news[];
int lens[];
int init()
{
news[]='$',news[]='#';
int j=;
for(int i=;s[i]!='\0';i++)
news[j++]=tolower(s[i]),news[j++]='#';
news[j]='\0';
return j;
}
int manacher()
{
int len=init(),mx=,id,maxlen=;
for(int i=;i<len;i++)
{
if(i<mx) lens[i]=min(lens[*id-i],mx-i);
else lens[i]=; while(news[i-lens[i]]==news[i+lens[i]])
lens[i]++; if(mx<i+lens[i]) id=i,mx=lens[i]+i;
maxlen=max(maxlen,lens[i]-);
}
return maxlen;
}
int main()
{
while(gets(s))
{
printf("%d\n",manacher());
} return ;
}
上一篇:Spark机器学习笔记一


下一篇:巧妙使用Contains()方法查找一个数是否在某堆数中