您的位置:首页 > 其它

LeetCode: Palindrome Partitioning II 解题报告

2014-12-06 22:28 204 查看
Palindrome Partitioning II

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.

public class Solution {
public int minCut(String s) {
if (s == null || s.length() == 0) {
return 0;
}

int len = s.length();

// D[i]: 前i 个字符切为回文需要的切割数
int[] D = new int[len + 1];
D[0] = -1;

// P[i][j]: S.sub(i-j) is a palindrome.
boolean[][] P = new boolean[len][len];

for (int i = 1; i <= len; i++) {
// The worst case is cut character one by one.
D[i] = i - 1;
for (int j = 0; j <= i - 1; j++) {
P[j][i - 1] = false;
if (s.charAt(j) == s.charAt(i - 1) && (i - 1 - j <= 2 || P[j + 1][i - 2])) {
P[j][i - 1] = true;
D[i] = Math.min(D[i], D[j] + 1);
}
}
}

return D[len];
}
}


View Code

GITHUB:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/dp/MinCut_1206.java
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: