Palindrome Partitioning II
Total Accepted: 3698 Total Submissions: 21952 My Submissions
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.
我以为应该像Palindrome Partitioning用BFS或者DFS来,发现超时。
超时的原因应该是做了很多重复的搜索,就像递归总是重复计算,迭代就会好很多。
参考各种大牛的代码,应该用DP。
int len = s.length();
声明两个数组,int []cutArr = new int[len+1];
int [][]dp = new int[len][len];
其中cutArr[i] 表示从位置i到len-1成为回文子串的最小划分。
dp[i][j]表示子串s.substring(i,j+1)是否为回文子串。
初始化时,dp[i][i] = 1;
如果s.charAt(i) == s.charAt(j),并且dp[i+1][j-1] = 1,那么dp[i][j] = 1;
更新cutArr[i] = Math.min(cutArr[i],cutArr[j+1]+1);这句话的含义是,
从位置i到len-1的最小划分为:如果子串i到j是回文串,那么最小划分就应该更新为
(从i到j应该是一个划分,加上从j到len-1的最小划分)和(从i到len-1的划分)的最小值。
因为cutArr[i]依赖于比i大的cutArr,所以应该倒序计算。
Java AC
public class Solution {
public int minCut(String s) {
if(s == null || "".equals(s.trim())){
return 0;
}
int len = s.length();
int cutArr[] = new int[len+1];
int dp[][] = new int[len][len];
for(int i = len-1; i >= 0; i--){
cutArr[i] = Integer.MAX_VALUE;
for(int j = i; j < len; j++){
if(s.charAt(i) == s.charAt(j)){
if(j - i < 2 || dp[i+1][j-1] == 1){
dp[i][j] = 1;
cutArr[i] = Math.min(cutArr[i],cutArr[j+1]+1);
}
}
}
}
return cutArr[0]-1;
}
}
参考http://blog.csdn.net/yutianzuijin/article/details/16850031