Title Link: https://leetcode.com/problems/palindrome-partitioning-ii/
Topic:
Given a string s, partition s such that every substring of the partition are a palindrome.
Return the minimum cuts needed for a palindrome partitioning of S.
For example, given s = "AaB",
Return 1 since the palindrome partitioning ["AA", "B"] could be produced using 1 cut.
Ideas:
Dp
C[i] means that a string from subscript 0~i is composed of at least a few palindrome strings.
DP[I][J] Indicates whether a string of subscript j~i is a palindrome
State transition equation:
0<=j<=i
If J~i is a palindrome string
C[i]=min{c[j-1]+1,c[i]}
Here to determine whether J~i is a palindrome can not be violent judgment or will time out, need to use the results previously judged. Even if Charat[j]==charat[i] &&dp[j+1][i-1], then Dp[j][i] is also a palindrome string.
Here to pay attention to the boundary situation, that is, when j=i or j+1==i, if charat[j]==charat[i], then J~i is also palindrome string, to prevent the appearance of the J+1>i-1 judgment.
Time complexity O (n^2), Spatial complexity O (n^2).
Algorithm:
PublicintMincut (String s) {if(S.length() ==0)return 0;intC[] = newint[S.length()];//0~i string minimum is a combination of several palindrome stringsBoolean dp[][] = new Boolean[s.length()][s.length()];//Whether the string from I~j is a palindrome for(inti =0; I < S.length(); i++) {Dp[i][i] =true; C[i] = i +1; for(intj =0; J <= I; J + +) {if(S.charat (j) = = S.charat (i) && (j = = I | | J +1= = I | | Dp[j +1][i-1]) {Dp[j][i] =true;if(J >0) {C[i] = Math.min(C[i], c[j-1] +1); }Else{C[i] = Math.min(C[i],1); } } } }returnC[s.length() -1] -1; }
"Leetcode" Palindrome partitioning II