B1040 Longest Symmetric String (区间DP)

B1040 Longest Symmetric String (25分)

求字符串中的最长回文串

  • 普通模拟

枚举端点O(n*n),判断是否回文O(n),因此总的复杂度是O(n^3).

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string.h>
#include <cmath>
#include <math.h>
#include <vector>
#include <queue>
#include <map>
#include <set>
#include <stack>
#define lowbit(i)((i)&(-i))
using namespace std;
typedef long long ll;
const int MAX=21;
const int INF=0x3f3f3f3f;
const int MOD=1000000007;
const int SQR=633;
string s;
bool check(int st,int ed)
{
    while(st<ed)
    {
        if(s[st]==s[ed])
        {
            st++;
            ed--;
        }
        else if(s[st]!=s[ed])
            return false;
    }
    return true;
}
int main()
{
    int x,y,flag=0,maxlen=0;
    getline(cin,s);
    for(int i=0;i<s.size();i++)
    {
        for(int j=s.size()-1;j>i;j--)
        {
           if(check(i,j))
           {
               x=i;
               y=j;
               flag=1;
               maxlen=max(maxlen,y-x+1);
           }
        }
    }
    if(flag==1)
    printf("%d\n",maxlen);
    else
    printf("1\n");
    return 0;
}


  • 区间dp

    20882701-3ccba267cd2e647c.png
    枚举容易出错的地方

边界状态两种:dp[i][i]=1或dp[i][i+1]=(s[i]==s[i+1])?1:0

因此以字串的长度和字串的初始位置进行枚举,即第一遍将字串长度为3的全部求出,再长度为4...
时间复杂度O(n*n)

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string.h>
#include <cmath>
#include <math.h>
#include <vector>
#include <queue>
#include <map>
#include <set>
#include <stack>
#define lowbit(i)((i)&(-i))
using namespace std;
typedef long long ll;
const int MAX=1001;
const int INF=0x3f3f3f3f;
const int MOD=1000000007;
const int SQR=633;
int dp[MAX][MAX];
int main()
{
    string s;
    getline(cin,s);
    memset(dp,0,sizeof(dp));
    int len=s.length(),ans=1;
    for(int i=0;i<len;i++)
    {
        dp[i][i]=1;
        if(i<len-1)
        {
            if(s[i]==s[i+1])
            {
                dp[i][i+1]=1;
                ans=2;
            }
        }
    }
    for(int l=3;l<=len;l++)
    {
        for(int i=0;i<len-l+1;i++)
        {
            int j=i+l-1;
            if(dp[i+1][j-1]==1&&s[i]==s[j])
            {
                dp[i][j]=1;
                ans=l;
            }
        }
    }
    printf("%d\n",ans);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值