palindrome Partitioning II
Given A string s, cut s into some substrings such that every substring is a palindrome.
Return the minimum cuts needed for a palindrome partitioning of s.
Example
For example, given s = "AaB",
Return 1 since the palindrome partitioning ["AA", "B"] could be produced using 1 cut.
Solution:
This problem must be memorized, mastered, the problem contains two DP.
First of all, this question is asked minimum cuts, naturally want to move back, the topic gave a string s, first go according to one-dimensional dynamic consideration, first define a result[] store DP results.
Consider the four main elements:
Status: F (x) = minimum tangent of string at the end of the X position.
Transfer equation: F (i) = Min{f (i), F (j) + 1} && s String from J + 1 to I-bit also need to be palindrome string ==> f (i) = Min (f (j) + 1) && s.substring (j + 1-1, i-1) is a palindrome
Initialization: Think about it, a single letter is definitely a palindrome string, so, the length of n strings, the maximum can be cut into the n-1 palindrome string (the middle of each letter cut), so is f (i) = I-1, and f (0) =-1, which is to ensure that the first single letter by the program identified as a legitimate palindrome.
As a result, F (s.length ());
The first DP came out, now look, judging palindrome string, if not DP words, then time complexity O (n), the total time complexity of n three times, too high. So you have to use memory search or DP optimizer.
To determine the palindrome string DP:
Status: Result[i][j] indicates that substrings ending from I to J are not palindrome strings
Transfer equation: result[i][j] = result[i + 1][j + 1] && s.charat (i) = = S.charat (j)
Initialization, this is the process from both sides, tightening to the middle, so the end may be collapsed to a letter, or two letters (depending on the total length is singular or even). So initialize all individual letters, and strings with substring lengths of 2
Result: return all result[][]
Public classSolution {/** * @params A String *@returnAn integer*/ Private Boolean[] Getispalindrome (String s) {Boolean[[] result =New Boolean[S.length ()][s.length ()]; for(inti = 0; I < s.length (); i++) {Result[i][i]=true; } for(inti = 0; I < S.length ()-1; i++) {Result[i][i+ 1] = (S.charat (i) = = S.charat (i + 1)); } for(inti = 2; I < s.length (); i++){ for(intj = 0; J + I < s.length (); J + +) {//j = Start pos; i = substring len;Result[j][j + i] = (result[j + 1][j + i-1] && S.charat (j) = = S.charat (j +i)); } } returnresult; } Public intmincut (String s) {int[] result =New int[S.length () + 1]; if(s = =NULL|| S.length () = = 0){ return0; } //Initial for(inti = 0; I <= s.length (); i++) {Result[i]= I-1; } Boolean[] Ispalindrome =Getispalindrome (s); // for(inti = 1; I <= s.length (); i++){ for(intj = 0; J < I; J + +){ if(ispalindrome[j][i-1]) {Result[i]= Math.min (Result[i], result[j] + 1); } } } returnresult[s.length ()]; }};
View Code
[Lintcode] Palindrome Partitioning II