palindrome 回文 /// Manacher算法

判断最长不连续回文

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

    return 0;
}

过程如图

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[205],news[505];
int lens[505];
int init()
{
    news[0]='$',news[1]='#';
    int j=2;
    for(int i=0;s[i]!='\0';i++)
        news[j++]=tolower(s[i]),news[j++]='#';
    news[j]='\0';
    return j;
}
int manacher()
{
    int len=init(),mx=0,id,maxlen=0;
    for(int i=1;i<len;i++)
    {
        if(i<mx) lens[i]=min(lens[2*id-i],mx-i);
        else lens[i]=1;
        
        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]-1);
    }
    return maxlen;
}
int main()
{
    while(gets(s))
    {
        printf("%d\n",manacher());
    }

    return 0;
}

 

posted @ 2018-04-13 23:28  _Jessie  阅读(229)  评论(0编辑  收藏  举报