Given a string s, partition s such that every substring of the partition is a palindrome.
Return the minimum cuts needed for a palindrome partitioning of s.
Example:
Input: "aab"
Output: 1
Explanation: The palindrome partitioning ["aa","b"] could be produced using 1 cut.
*/
//label:Dynamic programming
/*思路:当前下标在i处,如果说check(A,0,i)为真,说明从A[0]-A[i]区间为一个回文串,此时,就让dp[i]=0,
表示不需要切割;如果为false,则让dp[i] = dp[i-1]+1,也就是前一个回文状态多切割一次,然后j从1到i进行遍历,
如果说check(A,j,i)为true,那么表示A[j]-A[i]为回文串,那么让dp[i]= min{dp[j-1]+1,dp[i]},表示(0-j-1)
状态切割一次使得子串全部回文次数小还是从i-1切割一次使得子串全部回文次数小,取其小者作为i这个状态的值。
*/
class Solution {
public boolean check(char[] A,int l,int r) {
if(l==r) return true;
else {
for(int i = l,j=r;i<=j;i++,j--) {
if(A[i]!=A[j]) return false;
}
return true;
}
}
public int minCut(String s) {
char[] A = s.toCharArray();
int n = A.length;
int[] dp = new int[n];
dp[0] = 0;
for(int i = 1;i < n;i++) {
if(check(A, 0, i)) {
dp[i] = 0;
}
else {
dp[i] = dp[i-1]+1;
}
for(int j = 1;j <= i;j++) {
if(check(A, j, i)) {
dp[i] = Math.min(dp[j-1]+1, dp[i]);
}
}
}
return dp[n-1];
}
}