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]);
}
}