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.
For example, given s = "aab"
,
Return 1
since the palindrome partitioning ["aa","b"]
could be produced using 1 cut.
和 Word Break 差不多。都是类似的DP.这里是最优子结构就是该index 是最小分割数,所以 dp[i] = dp[j] + 1 if i~j is palindrome.
要注意的是,判断一个字符串是否是回文,也要用DP,不然会超时。
public class Solution {
public int minCut(String s) {
int[] dp = new int[s.length()+1];
boolean[][] palindrome = new boolean[s.length()][s.length()];
for(int i = 0; i < dp.length; i++) dp[i] = s.length()-i;
for(int i = s.length()-1; i>=0; i--){
for(int j = i; j < s.length(); j++){
if(s.charAt(i)==s.charAt(j) && (j-i<2 || palindrome[i+1][j-1])){
palindrome[i][j] = true;
dp[i] = Math.min(dp[i],dp[j+1]+1);
}
}
}
return dp[0]-1;
}
}