题目描述
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",
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.
动态规划总是练不好,强行递归每次又都超时,真的是烦。
思路:从头开始,第一个元素单独切割一定是回文。
dp[i]表示以第i个字符结尾分割成回文组的最小分割数。
isParli[i][j]表示从第i个字符到第j个字符能否构成回文。
isParli[i][j] = ((charAt(i) == charAt(k) ) && (i - k < 2 || isParli[i - 1][k + 1]));
return最后一个dp[]即为结果。
public class Solution {
public int minCut(String s) {
int [] dp = new int [s.length() + 1];
boolean [][] isParli = new boolean [s.length() + 1][s.length() + 1];
dp[0] = -1;
for(int i = 2; i <= s.length(); ++i)
dp[i] = Integer.MAX_VALUE;
for(int i = 1; i <= s.length(); ++i){
for(int k = 1; k <= i; ++k){
if((i - k < 2 || isParli[i - 1][k + 1]) && s.charAt(i - 1) == s.charAt(k - 1)){
isParli[i][k] = true;
dp[i] = Math.min(dp[i],dp[k - 1] + 1);
}
}
}
return dp[s.length()];
}
}