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”,
Return1since the palindrome partitioning[“aa”,”b”]could be produced using 1 cut.
解题思路:从后往前遍历,判断i到length之间所需要的最小cut。判断s[i][j]是否为回文字符串的方法是s.charAt(i)==s.charAt(j),j-i<2||palindrome_map[i+1][j-1]==1,然后保存i与j之间的回文关系,如果i到j为回文则需要修改cut_num_array,否则继续遍历。每次初始化cut_num_array都是以s.length() - i是为了保证cut的最大值,这是为了方便。
public int minCut(String s) {
if(s==null||s.length()==0||s.length()==1) {
return 0;
}
int[][] palindrome_map = new int[s.length()][s.length()];
/*用来保存所有的回文字符串,然后用cut_num_array记录总共的剪切数,遍历i和j之间的字符串*/
int[] cut_num_array = new int[s.length() + 1];
for(int i=s.length()-1;i>=0;i--) {
cut_num_array[i] = s.length()-i;//cut_num_array[i]=cut_num_array[i]+1
for(int j=i;j<s.length();j++) {
if(s.charAt(i)==s.charAt(j)) {
if(j-i<2||palindrome_map[i+1][j-1]==1) {
palindrome_map[i][j]=1;
cut_num_array[i] = Math.min(cut_num_array[i], cut_num_array[j+1]+1);
}
}
}
}
return cut_num_array[0] - 1;
}