Everything is still a Palindrome

Every string is made up of palindromes. For example, the string papaya can be formed in the following way :

1
2
3
pap + aya
p + apa + y + a
p + a + p + a + y + a

We need at least two palindromes to form papaya = pap + aya . This file contains a string of length 1000. What is the minimum number of palindromes do we need to construct the string?

Here are 4 sample inputs and their corresponding output for clarification.

Sample Input

1
2
3
4
abc
abcb
abcba
abcbacabcb

Sample Output

1
2
3
4
3
2
1
2


This is a follow-up of this problem.


The answer is 304.

This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try refreshing the page, (b) enabling javascript if it is disabled on your browser and, finally, (c) loading the non-javascript version of this page . We're sorry about the hassle.

1 solution

Arthur Komatsu
Sep 29, 2018

This problem has a O ( n 2 ) O(n ^ 2) dynamic programming (DP) solution ( n n as the string size). There are a few different implementations, the following one is one of them:

Consider that the string has size n n , the first position is indexed at 1 1 and s [ i . . . j ] s[i...j] is a substring of s s which starts at i i and ends at j j .

First, we have to check if the substring s [ i . . . j ] s[i...j] is a palindrome for all 1 i , j n 1 \leq i, j \leq n . It can be done using a simple DP: s [ i . . . j ] s[i...j] is a palindrome if s [ i ] = s [ j ] s[i] = s[j] and s [ i + 1... j 1 ] s[i+1...j-1] is a palindrome. If i j i \geq j , we define that s [ i . . . j ] s[i...j] is a palindrome. This preprocess method has O ( n 2 ) O(n^2) complexity. Note that checking if s [ i . . . j ] s[i...j] is a palindrome in the naive way (using a for loop) has O ( n 3 ) O(n^3) complexity for all 1 i , j n 1 \leq i, j \leq n .

Now, we make a second DP to solve the problem. Consider d p [ i d x ] dp[idx] the answer for the problem for the substring s [ 1... i d x ] s[1...idx] . Then for all 1 i i d x 1 \leq i \leq idx , if s [ i . . . i d x ] s[i...idx] is a palindrome, we can split the string into s [ 1... i 1 ] s[1...i-1] and s [ i . . . i d x ] s[i...idx] . Thus, the answer for d p [ i d x ] dp[idx] is the minimum of d p [ 1... i 1 ] + 1 dp[1...i-1] + 1 for all i i such that s [ i . . . i d x ] s[i...idx] is a palindrome. The answer for the problem is d p [ n ] dp[n] . This has O ( n 2 ) O(n^2) complexity, so the overall complexity is O ( n 2 ) O(n^2) , which is fast for n = 1000 n = 1000 . You can check my C++ implementation here .

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...