Palindrome Partitioning - lightOJ 1044-求分解最少回文字符串

本文介绍了一种通过动态规划算法解决字符串最小回文分割数问题的方法。针对给定的字符串,算法确定将其划分为最少数量的回文子串所需的最小分割次数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Time Limit: 1 second(s)Memory Limit: 32 MB

A palindrome partition is the partitioning of a string such that each separate substring is a palindrome.

For example, the string "ABACABA" could be partitioned in several different ways, such as {"A","B","A","C","A","B","A"}, {"A","BACAB","A"}, {"ABA","C","ABA"}, or {"ABACABA"},among others.

You are given a string s. Return the minimum possible number of substrings in a palindrome partition of s.

Input

Input starts with an integer T (≤ 40), denoting the number of test cases.

Each case begins with a non-empty string s of uppercase letters with length no more than 1000.

Output

For each case of input you have to print the case number and the desired result.

Sample Input

Output for Sample Input

3

AAAA

ABCDEFGH

QWERTYTREWQWERT

Case 1: 1

Case 2: 8

Case 3: 5

题目大意:

给出一个字符串,问将其分为回文字符串的最小数量,回文字符串,不是回文序列~

思路:

dp[i]表示字符串中区间c[0]-c[i]分为回文子串的最小数量,显然dp[i]的初值赋为i+1,

之后枚举区间的结束端点i和中间点j,如果区间j-i恰好为回文串,那么可以将这一段分为一个子串,

也可以暂时不分,更新dp[i]=min(dp[i],dp[j]+1),最后输出dp[len] 

代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#define maxn 1100
#define inf 0x3fffffff
using namespace std;

char c[maxn];
int dp[maxn];

bool panduan(int i,int j)
{
    for(int pos=i; pos<=(i+j)/2; pos++)
        if(c[pos]!=c[j+i-pos])
            return false;
    return true;
}

int main()
{
    int t,cas=1;
    cin>>t;
    while(t--)
    {
        scanf("%s",c);
        int n=strlen(c)-1;
        if(panduan(0,n)==1)
        {
            printf("Case %d: 1\n",cas++);
            continue;
        }
        for(int i=0; i<=n; i++)
        {
            dp[i]=i+1;
        }
        for(int i=0; i<=n; i++)
            for(int j=0; j<=i; j++)
            {
                if(panduan(j,i)==1)
                    dp[i]=min(dp[i],dp[j-1]+1);
            }
        printf("Case %d: %d\n",cas++,dp[n]);
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值