您的位置:首页 > 其它

Leetcode 132. Palindrome Partitioning II

2017-02-10 11:56 423 查看
function f(i) tells the minimum cuts for sub string (0, i).

f(0) = 0.

f(1) = min(0 if (0, 1) is a palindrome, 

  f(0)+1 b/c (1, 1) is a palindrome)

f(2) = min(0 if (0, 2) is a palindrome,

  or f(0)+1 if (1, 2) is a palindrome,

  or f(1)+1)

f(3) = min(0 if (0, 3) is a palindrome,

  or f(0)+1 if (1, 3) is a palindrome,

  or f(1)+1 if (2, 3) is a palindrome,

          or f(2)+1)

Because we frequently visit isPalindrome, so we save the palindrome info into a 2D array which also using DP. 

public class Solution {
public int minCut(String s) {
// cuts[i] means the minimum cuts of sub string (0, i)
int[] cuts = new int[s.length()];
boolean[][] isPalindrome = buildPalinTab(s);

for (int i=1; i<s.length(); i++) {

4000
int min = Integer.MAX_VALUE;
if (isPalindrome[0][i]) {
cuts[i] = 0;
} else {
for (int j=1; j<=i; j++) {
if (isPalindrome[j][i] && (min > cuts[j-1]+1)) {
min = cuts[j-1]+1;
}
}
cuts[i] = min;
}
}

return cuts[s.length()-1];
}

// build isPalindrome table using dp
private static boolean[][] buildPalinTab(String s) {
boolean[][] dp = new boolean[s.length()][s.length()];

for (int i=s.length()-1; i>=0; i--) {
for (int j=i; j<s.length(); j++) {
if (s.charAt(i) == s.charAt(j)) {
if (j - i < 3) {
dp[i][j] = true;
} else {
dp[i][j] = dp[i+1][j-1];
}
}
}
}

return dp;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: