poj3974 Palindrome(Hash)(二分)

题意

给定一个长度为n的字符串,求它的最长回文串。

题解1

Manachar
这个是正正解,时间复杂度仅为O(n),但不作为这次的主讲。

题解2

hash+二分
又是一道判断子串是否相同的问题,hash这个O(n)预处理,O(1)判断的绝B首选。
但是这题需要顺着hash一次,逆着hash一次,因为回文串讲的是对称。
实现时,枚举一个点或者两个点作为中心,然后向两边扩展。扩展满足二分性。二分+hash判断真是绝配,这个搭配可以很好地解决两个串的最长公共前缀的问题
hash+二分的时间复杂度为O(n logn)。

代码

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef unsigned long long ull;
const int maxl=1000010;
const int P=131;ull power[maxl];//power[i]=P^i

char s[maxl];int len;
ull h1[maxl],h2[maxl];

bool check(int l1,int r1,int l2,int r2)//比较[l1,r1]与[r2,l2]是否相同
{
    ull tmp1=h1[r1]-h1[l1-1]*power[r1-(l1-1)];
    ull tmp2=h2[r2]-h2[l2+1]*power[(l2+1)-r2];//注意:是l2+1不是l2-1 
    return tmp1==tmp2;
}

int main()
{
    power[0]=1;for(int i=1;i<maxl;i++) power[i]=power[i-1]*P;
    int T=0;
    while(scanf("%s",s+1),s[1]!='E')
    {
        len=strlen(s+1);
        h1[0]=h2[len+1]=0;
        for(int i=1;i<=len;i++) h1[i]=h1[i-1]*P+s[i]-'a';
        for(int i=len;i>=1;i--) h2[i]=h2[i+1]*P+s[i]-'a';
        
        int mx=1;
        int l,r,ans;
        for(int i=1;i<=len;i++)
        {
            l=1;r=min(i-1,len-i);ans=0;//单点中心
            while(l<=r)
            {
                int mid=l+r>>1;
                if(check(i-mid,i-1,i+mid,i+1))
                {
                    ans=mid;
                    l=mid+1;
                }
                else r=mid-1;
            }
            mx=max(mx,2*ans+1);
            
            if(s[i]!=s[i+1]) continue;//双点中心
            l=1;r=min(i-1,len-(i+1));ans=0;
            while(l<=r)
            {
                int mid=l+r>>1;
                if(check(i-mid,i-1,i+1+mid,i+2))
                {
                    ans=mid;
                    l=mid+1;
                }
                else r=mid-1;
            }
            mx=max(mx,2*(ans+1));
        }
        
        printf("Case %d: %d\n",++T,mx);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/A_Bright_CH/article/details/81515415
今日推荐