/** 132. Palindrome Partitioning II * 12.29 by Mingyang * First set DP variable cuts[len+1]. Cuts[i] Represents the number of cuts from position I to the Len position (inclusive, that is, [I, Len]) (The Len position is empty). * Initially, it is len-i. For example Aab,cuts[0]=3, is the worst case of every character must be cut: a|a|b| ' ‘。 CUTS[1] = 2, starting from the I=1 position, a|b| ' ‘。 , * cuts[2] = 1 b| ' ‘。 Cuts[3]=0, which is the position of the Len, is a null character and does not require cutting. * The above cuts array is used to help calculate the minimum cuts. * Also requires a DP two-dimensional array matrixs[i][j] to represent the string [I,j] from the first position (inclusive) to the J-position (inclusive) is a palindrome. * How to tell if the string [I,j] is a palindrome? * 1. Matrixs[i+1][j-1] is a palindrome and S.charat (i) = = S.charat (j). * 2. I==j (I,j is with one character) * 3. J=i+1 (i,j adjacent) and S.charat (i) = = S.charat (j) * When the string [I,j] is a palindrome, the minimum cut number from the I position to the string Len position can be updated, so that is the minimum C from the j+1 position to the Len position UT number plus [i,j]| [J+1,len-1] In the middle of this cut. * That is, math.min (Cuts[i], cuts[j+1]+1) * finally returns CUTS[0]-1. The final result is to remove the extra one cut for the position of the first Len. */ Public intmincut (String s) {intn =s.length (); BooleanIspal[][] =New Boolean[N][n]; intCut[] =New int[n]; for(intj = 0; J < N; J + +) {Cut[j]= J;//minimum cut number from 0 to J for(inti = 0; I <= J; i++) { //if the substring S[I...J] is a palindrome string if(S.charat (i) = = S.charat (j) && (j-i <= 1 | | ispal[i + 1][j-1])) {Ispal[i][j]=true; if(I > 0) Cut[j]= Math.min (Cut[j], cut[i-1] + 1); //every time you encounter a palindrome will need to update this cut, because if there is a palindrome will reduce cut, you can change the second half of the palindrome string into 0, just add the front plus 1 ElseCut[j]= 0;//if S[0...J] is a palindrome, it means that no cutting is required } } } returnCut[n-1]; }
Palindrome Partitioning II