Palindrome Partitioning II
Cut a string into palindromes with as few cuts as possible, using the best answer for every prefix.
Given a string s
Example 1
Output: 1
Explanation: "aa" | "b" needs one cut.
Example 2
Output: 0
Example 3
Output: 2
Explanation: "a" | "bccb" | "c".
The Idea
One letter on its own always reads the same both ways, so cutting before every letter always works. In Example 3, "abccbc"
Example 3 needs only two: "a" | "bccb" | "c". The middle piece, "bccb", is the same backwards, so it stays whole. But six letters have five gaps between them, and each gap can be cut or not, so there are 32 ways to cut the string. That number doubles with every extra letter. Can we find the best split without trying them all?
Look at the end of the string instead of the start. Whatever the best split is, its last piece ends at the last letter, and it is a palindrome. In "abccbc"
If the last piece is "c", the letters before it, "abccb", need their own best split, plus one cut in front of the "c". If the last piece is "cbc", the letters before it are "abc", again plus one cut. So the question for the whole string becomes the same question for a shorter piece from its beginning. Look at the picture below.
The row labelled "fewest cuts up to here" holds the fewest cuts needed for the letters from position 0 up to each position. Such a piece, taken from the very beginning of a string, is called a prefix. Under position 4 is 1, because "abccb" splits as "a" | "bccb". Under position 2 is 2, because "abc" has no palindrome longer than one letter.
Last piece "c" then costs 1 + 1 = 2 cuts, last piece "cbc" costs 2 + 1 = 3, and the smaller, 2, goes under position 5. That is the answer to Example 3. Every number in the row comes from numbers to its left, so filling the row from left to right always has the numbers it needs ready.
Solution Approach
Turning that into code means seeing why a plain search is slow, then settling two things: what each entry of the cuts table means, and how to check a piece quickly.
Trying every first piece
Why not simply search? Pick a palindrome that starts the string, solve the rest of the string the same way, then step back and pick a longer first piece, keeping the split with the fewest cuts. That pick, solve and step back pattern is called backtracking, and it does give the right answer.
But it answers the same question many times. A run that counts the calls shows it: for a string of ten a's, the search makes 1,024 calls, and asks "what is the fewest cuts from position 5 on?" 16 times. With twenty a's it makes 1,048,576 calls.
The fix is to work out the answer for each prefix once and keep it in a table, so a longer prefix only reads it. Solving every prefix of the string once, shortest first, and reading the stored counts instead of searching again is called
The cuts table
What does one entry mean? cuts[j]j"abccbc"ncuts[n - 1]
How is cuts[j]ijijs[i..j]icuts[i - 1] + 1i
cuts[j]j
Telling whether a piece is a palindrome
How do we check s[i..j]j - is[i..j]s[i+1..j-1]
"bccb" has b at both ends and "cc" inside, so it passes. A piece of one or two letters has no inside to check, so matching ends are enough. The results go into a table of true and false values, isPal[i][j]jj - 1
Java Solution
The loops live in a helper, cutsTablecutsmain
- First, create the two tables for a string of length
:n , anisPal byn grid of booleans, all false at the start, andn , an array ofcuts numbers.n - An outer loop moves
from 0 toj , the end of the prefix being solved, and setsn - 1 tocuts[j] , the cut-before-every-letter split.j - Inside, a second loop moves
from 0 toi , over every place the last piece could begin. Whenj equalss.charAt(i) , and the piece has at most two letters (s.charAt(j) ) or its insidej - i < 2 is true, it setsisPal[i + 1][j - 1] to true.isPal[i][j] - For each such palindrome it updates
: to 0 ifcuts[j] is 0, otherwise to the smaller ofi andcuts[j] .cuts[i - 1] + 1 - When both loops are done,
returnscutsTable , andcuts , the method that answers the problem, returns its last entry.minCut
The main
import java.util.Arrays;
public class PalindromePartitioningII {
// cuts[j] = fewest cuts that split the first j + 1 letters, s[0..j], into palindromes
static int[] cutsTable(String s) {
int n = s.length();
boolean[][] isPal = new boolean[n][n]; // isPal[i][j]: s[i..j] reads the same both ways
int[] cuts = new int[n];
for (int j = 0; j < n; j++) {
cuts[j] = j; // worst case: a cut before every letter
for (int i = 0; i <= j; i++) {
if (s.charAt(i) == s.charAt(j) && (j - i < 2 || isPal[i + 1][j - 1])) {
isPal[i][j] = true; // s[i..j] can be the last piece
cuts[j] = (i == 0) ? 0 : Math.min(cuts[j], cuts[i - 1] + 1);
}
}
}
return cuts;
}
public static int minCut(String s) {
int[] cuts = cutsTable(s);
return cuts[s.length() - 1];
}
public static void main(String[] args) {
System.out.println(minCut("aab"));
System.out.println(minCut("a"));
System.out.println(minCut("abccbc"));
System.out.println(minCut("aaaa"));
System.out.println(minCut("abcd"));
System.out.println(minCut("abacaba"));
System.out.println("cuts for abccbc: " + Arrays.toString(cutsTable("abccbc")));
}
}
Running it prints:
1
0
2
0
3
0
cuts for abccbc: [0, 1, 2, 2, 1, 2]
"aab" gives 1, from "aa" | "b", and "abccbc" gives 2, from "a" | "bccb" | "c". The 0 for "aaaa" and the 0 for "abacaba" both come from the i == 0
Look at the last line: [0, 1, 2, 2, 1, 2]cuts[0] + 1 = 1
Why is the check j - i < 2j - i < 1j - i < 1isPal[i + 1][j - 1]
Complexity
The work is the two loops over pairs of positions, and the memory is the two tables.
- Time: O(n2), because the inner loop visits each pair of positions
once, about n2/2 pairs, and each visit is one letter comparison, one table lookup and at most one minimum.i <= j - Space: O(n2), because
keeps one true or false value for every pair of positions, whileisPal adds only n numbers.cuts
Checking palindromes by growing outward from each middle letter, instead of storing isPal