8922 最长回文子串

时间限制:1000MS  代码长度限制:10KB
提交次数:0 通过次数:0

题型: 编程题   语言: G++;GCC

Description

一个字符串正着读和倒着读是一样的,则称回文串。
给定一个长度为字符串S,求其最长回文子串的长度。

输入格式

输入一个字符串S,均为小写字符,长度最多1000000个小写字符。

输出格式

输出最长回文子串的长度。

输入样例

abcbabcbabcba

输出样例

13

 

#include<iostream>
#include<algorithm>
#include<sstream>
#include<math.h>
#include<vector>
#include<queue>
#include<list>
#include<stack>
#include<map>
#include<set>
#include<string>
#include<stdio.h>
#include<ctype.h>
#include<cstring>
#include<cstdlib>
#include<iomanip>
using namespace std;
typedef  long long ll;
const ll p = 10;
ll pw[100005], hx[100005];
int main()
{
	//freopen("in.txt", "r", stdin);
	//fill_n(pw, 100000, 1);
	ios::sync_with_stdio(0);
	string s;
	ll ans = 1;
	cin >> s;
	for (int i = 1; i < s.size(); i++)
	{
		int l=i-1, r=i+1;
		ll tmp = 1;
		while (l >= 0 && r < s.size())
		{
			if (s[l] == s[r])
			{
				tmp+=2;
				l--, r++;
			}
			else
			{
				break;
			}
		}
		ans = max(ans, tmp);
		l = i, r = i + 1;
		tmp = 0;
		while (l >= 0 && r < s.size())
		{
			if (s[l] == s[r])
			{
				tmp += 2;
				l--, r++;
			}
			else
			{
				break;
			}
		}
		ans = max(ans, tmp);
	}
	cout << ans;
}

 下面代码二分法比较好理解,l是左端点,r是右端点。

#include <iostream>
#include<string>
typedef unsigned long long ll;
using namespace std;
string s;
ll n, p=131,hx1[1000005],hx2[1000005],pw[1000005]= {1};
int check(ll pos)
{
    int p=1,ans=0,len=0;
    while(p)
    {
        /**< 用倍增法或二分法都可以尝试检查最大回文子串,此处是倍增法*/
        if(len+p>pos-1||len+p>n-pos)
        {
            p/=2;
            continue;
        }
        else
            len=ans+p;
        if(hx1[pos-1]-hx1[pos-len-1]*pw[len]==hx2[pos+1]-hx2[pos+len+1]*pw[len])
        {
            ans=len;
            p*=2;
        }
        else
            len=ans,p/=2;
    }
    return 2*ans+1;
}
int check2(ll pos)
{
    int l=1,r=min(pos,n-pos),ans=0;
    while(l<=r)
    {
        int mid=(l+r)>>1;
        if(hx1[pos]-hx1[pos-mid]*pw[mid]==hx2[pos+1]-hx2[pos+mid+1]*pw[mid])
        {
            ans=mid;
            l=mid+1;
        }
        else
            r=mid-1;
    }
    return 2*ans;
}
int main()
{
    ios::sync_with_stdio(0),cin.tie(0);
    int i,j,c=0;
    for(i=1; i<=1000000; i++)
        pw[i]=pw[i-1]*p;
    cin>>s;
    int ans=0;
    n=s.size();
    hx2[n+1]=0;
    for(i=0; i<n; i++)
        hx1[i+1]=hx1[i]*p+s[i]-'a'+1;
    for(i=n-1; i>=0; i--)
        hx2[i+1]=hx2[i+2]*p+s[i]-'a'+1;
    for(i=1; i<=n; i++) /**< 枚举i为中心和i为左起点的最大回文子串 */
    {
        int len1=check(i),len2=check2(i);
        ans=max(ans,max(len1,len2));
    }
    cout<<ans<<endl;
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值