码迷,mamicode.com
首页 > 其他好文 > 详细

最长回文子串

时间:2015-08-02 00:48:39      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:

len <1000000;

   F[i]= min(F[2*j-i],F[j]-2*(i-j)); j为小于i =  > j+F[j]/2 最大的;

技术分享
#include <iostream>
#include <algorithm>
#include <string.h>
#include <cstdio>
#include <vector>
using namespace std;
const int maxn = 1000005*2;
char s[maxn];
char str[maxn];
int ans;
int F[maxn];
void solve(int n)
{
       F[0]=1;
       int ma =0;
       for(int i=1; i<n; i++)
        {
            int d=ma*2 -i;
            int los=0;
            if(d<0)
                {
                    los=0;
                }
            else los=F[d];

            if( d>=0&&F[ma]-(i-ma)*2<0 )
                {
                    los=0;
                }
            else if(d>=0)
                los=min(los,F[ma]-(i-ma)*2);

            F[i]=los;

            if(i+F[i]/2> ma+F[ma]/2)
                ma=i;
            int L = i-los/2,R=los/2+i;

            while(L-1>=0&&R+1<n&&str[L-1]==str[R+1])
                {
                     L--;R++;
                }

            d=R-L+1;
            F[i]=d;
            if(i+F[i]/2> ma+F[ma]/2)ma=i;
            if(str[i]==#)
                {
                    d--;
                    if(d>0&&str[L]!=#)
                    {
                        ans=max( 2+max( (d-2)/2,0),ans);
                    }
                    else if(d>0)
                    {
                        ans=max(d/2,ans  );
                    }
                }
            else
                {
                    if(d>2&&str[L]!=#)
                        {
                            ans=max(ans, 1+(d-1)/2) ;
                        }
                    else if(d>2)
                        {
                            ans=max(ans, 1+(d-3)/2);
                        }
                }
        }
}
int main()
{
     int cas;
     scanf("%d",&cas);
     for( int cc =1; cc <=cas; cc++)
        {
           scanf("%s",s);
           int n =strlen(s);
           int loc=0;
           for(int i=0; i<n; i++)
            {
                str[loc++]=s[i];
                str[loc++]=#;
            }
           ans =1;
           solve(loc-1);
           printf("%d\n",ans);
        }

    return 0;
}
View Code

 

最长回文子串

标签:

原文地址:http://www.cnblogs.com/Opaser/p/4491394.html

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