Every string is made up of palindromes. For example, the string
papaya
can be formed in the following way :
1 2 3 |
|
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 |
|
Sample Output
1 2 3 4 |
|
This is a follow-up of this problem.
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.
This problem has a O ( n 2 ) dynamic programming (DP) solution ( 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 , the first position is indexed at 1 and s [ i . . . j ] is a substring of s which starts at i and ends at j .
First, we have to check if the substring s [ i . . . j ] is a palindrome for all 1 ≤ i , j ≤ n . It can be done using a simple DP: s [ i . . . j ] is a palindrome if s [ i ] = s [ j ] and s [ i + 1 . . . j − 1 ] is a palindrome. If i ≥ j , we define that s [ i . . . j ] is a palindrome. This preprocess method has O ( n 2 ) complexity. Note that checking if s [ i . . . j ] is a palindrome in the naive way (using a for loop) has O ( n 3 ) complexity for all 1 ≤ i , j ≤ n .
Now, we make a second DP to solve the problem. Consider d p [ i d x ] the answer for the problem for the substring s [ 1 . . . i d x ] . Then for all 1 ≤ i ≤ i d x , if s [ i . . . i d x ] is a palindrome, we can split the string into s [ 1 . . . i − 1 ] and s [ i . . . i d x ] . Thus, the answer for d p [ i d x ] is the minimum of d p [ 1 . . . i − 1 ] + 1 for all i such that s [ i . . . i d x ] is a palindrome. The answer for the problem is d p [ n ] . This has O ( n 2 ) complexity, so the overall complexity is O ( n 2 ) , which is fast for n = 1 0 0 0 . You can check my C++ implementation here .