原题链接在这里:https://leetcode.com/problems/palindrome-partitioning-ii/
这道题与Word Break相似。用DP来做,需要保留的历史信息就是到当前点能分成几块Palindrome, 用一个int数组res保留。每次更新res[i+1], 比较i+1和res[j]+1大小,取小的。因为单个letter肯定是palindrome, 所以肯定会被字典拆开,但[j...i]这一段可能是一个palindrome, 所以数量应更新成res[j]+1与i+1中较小的一个。
用二维boolean数组存储字典,boolean[i][j]表示从i到j这一段是否是回文。
Note: 1. helper当中判断使用dict[i+1][j-1]之前需先判定i,j 是否out of index了,这类问题都是如此,需先判断index有没有out of bound.
2. minCut中,双层loop的内层loop, j 是由 0 到 i, 判断isDic[j][i]是否为true.
AC Java:
public class Solution {
public int minCut(String s) {
if(s == null || s.length() == 0){
return 0;
}
int len = s.length();
boolean[][] isDic = helper(s);
int [] res = new int[len+1];
res[0] = 0;
for(int i = 0; i < len; i++){
res[i+1] = i+1;
for(int j = 0; j <= i; j++){ //error
if(isDic[j][i]){
res[i+1] = Math.min(res[i+1],res[j]+1);
}
}
}
return res[len] - 1;
}
//helper function builds dictionary
private boolean[][] helper(String s){
int len = s.length();
boolean[][] dict = new boolean[len][len];
for(int i = len-1; i>=0; i--){
for(int j = i; j < len; j++){
if(s.charAt(i) == s.charAt(j) && ((j-i)<2 || dict[i+1][j-1] )){ //error
dict[i][j] = true;
}
}
}
return dict;
}
}