We say a sequence of characters is a palindrome if it is the same written forwards and backwards. For example, ' racecar ' was a palindrome, but ' Fastcar ' was not. A partition of sequence of characters are a list of one or more disjoint non-empty groups of consecutive characters whose Concatenation yields the initial sequence.
For example,
(' Race ', ' car ') is a partition of ' racecar ' into the groups. Given a sequence of characters, we can always create a partition of these characters such this each group in the partition is a palindrome! Given This observation it's natural to ask:what are the minimum number of groups needed for a Given string such that ever Y group is a palindrome? For example:
• ' Racecar ' is already a palindrome, therefore it can being partitioned into one group.
• ' Fastcar ' does not contain no non-trivial palindromes, so it must is partitioned as (' F ', ' a ', ' s ', ' t ', ' C ', ' A ', ' R ') .
• ' AAADBCCB ' can be partitioned as (' AAA ', ' d ', ' BCCB ').
Input
Input begins with the number N of test cases.
Each test case consists of a single line of between 1 and lowercase letters, with no whitespace within.
Output
For each test case, output a line containing the minimum number of groups required to partition the input into groups of P Alindromes.
Sample Input
3
Racecar
Fastcar
Aaadbccb
Sample Output
1
7
3
In a string, find the minimum composition string
Problem Solving Ideas:
Use the enumeration method to raise the point to the end is a palindrome string, that is, to determine whether J-i is a palindrome string, if it is a single letter, it is also composed of a palindrome string
Program code:
1#include <cstdio>2#include <cstring>3 using namespacestd;4 #defineMAXN 10105 CharA[MAXN];6 intD[MAXN];7 intMinintXinty)8 {9 returnX<y?x:y;Ten } One BOOLLevelintLintR) A { - intM= (L+R)/2; - for(intI=l; i<=m; i++) the if(A[i]!=a[r-i+l])return false; - return true; - } - intMain () + { - intN; +scanf"%d",&n); A while(n--) at { -scanf"%s", A +1); - intM=strlen (A +1); -d[0]=0; - for(intI=1; i<=m+1; i++) -d[i]=1010; in for(intI=1; i<=m; i++) - for(intj=1; j<=i; J + +) to if(Level (j,i)) +D[i]=min (d[i],d[j-1]+1); -printf"%d\n", D[m]); the } * return 0; $}View Code
Dynamic programming--h Minimum palindrome string