码迷,mamicode.com
首页 > 编程语言 > 详细

palindrome 回文 /// Manacher算法

时间:2018-04-14 00:39:10      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:for   tps   string   main   lower   strong   ret   algo   code   

判断最长不连续回文

#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;
}

 

palindrome 回文 /// Manacher算法

标签:for   tps   string   main   lower   strong   ret   algo   code   

原文地址:https://www.cnblogs.com/zquzjx/p/8824747.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!