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.
一刷
题解:
初始定义一个一维数组minCuts,用来表示s.substring(0, i + 1)时的最小cut数。
再定义一个二维布尔数组isPalindrome,用来表示 s.substring(j, i)是否是palindrome。
核心算法是,假如isPalindrome[j][i]是palindrome,说明 j - 1至i + 1只需要1个cut, 因此对每一个i, minCuts[i]可以进行更新 - 比较现有 minCuts[i] 与 minCuts[j - 1] + 1。 这里也是一个一维的dp。
public class Solution {
public int minCut(String s) {
int len = s.length();
int[] minCuts = new int[len]; //minCuts[i] is min cut for s.substring(0, i+1)
boolean[][] isPalindrome = new boolean[len][len];
for(int i=0; i<len; i++){
minCuts[i] = Integer.MAX_VALUE;
for(int j=0; j<=i; j++){
if(s.charAt(j) == s.charAt(i)){//s.substring(j, i+1) is palindrome
if(i-j <=1 || isPalindrome[j+1][i-1]){
isPalindrome[j][i] = true;
if(j==0) minCuts[i] = 0;
else minCuts[i] = Math.min(minCuts[i], minCuts[j-1]+1);
}
}
}
}
return minCuts[len-1];
}
}
二刷
思路同上
public class Solution {
public int minCut(String s) {
int len = s.length();
int[] minCuts = new int[len];
Arrays.fill(minCuts, Integer.MAX_VALUE);
boolean[][] isPalin = new boolean[len][len];
for(int i=0; i<len; i++){
for(int j=0; j<=i; j++){
if(s.charAt(i) == s.charAt(j)){
if(i-j<=1 || isPalin[j+1][i-1]){
isPalin[j][i] = true;
if(j == 0) minCuts[i] = 0;
else minCuts[i] = Math.min(minCuts[i], minCuts[j-1]+1);
}
}
}
}
return minCuts[len-1];
}
}