Problem 299
Palindrome Partitioning Minimum Cuts
Hard · 30 pts · String, Dynamic Programming
Problem
You are given a string S. Cut it into consecutive pieces so that every piece is a palindrome (reads the same forwards and backwards). Find the minimum number of cuts needed. A string that is already a palindrome needs 0 cuts. First precompute which substrings are palindromes, for example by expanding around every centre. Then let cuts[i] be the minimum cuts for the first i characters: for every palindrome S[j..i - 1], cuts[i] can be cuts[j] + 1, with cuts[0] = -1 so that a whole-prefix palindrome costs 0.
Input
A single string S of lowercase letters.
Output
Print the minimum number of cuts.
Constraints
1 <= |S| <= 2000
Example input
aab
Example output
1
Explanation
"aab" is not a palindrome, so at least one cut is needed. Cutting it into "aa" and "b" gives two palindromes with one cut, so the answer is 1.