您的位置:首页 > 其它

[LeetCode] Palindrome Partitioning II

2014-04-24 17:55 411 查看
Total Accepted: 7469
Total Submissions: 43163

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) {
int len = s.length();
if (len == 0) return 0;

int[][] dp1 = new int[len][len];

for (int i = 0; i < len; i++) dp1[i][i] = 1;

for (int k = 1; k < len; k++) {
for (int i = 0; i < len - k; i++) {
int j = i + k;

if (((j == i+1) || (dp1[i+1][j-1] == 1)) && s.charAt(i) == s.charAt(j)) dp1[i][j] = 1;
}
}

// mincut from 0 to i
int[] dp2 = new int[len];

for (int i = 0; i < len; i++) dp2[i] = Integer.MAX_VALUE;

dp2[0] = 0;

for (int i = 0; i < len; i++) {
if (dp1[0][i] == 1) dp2[i] = 0;
else {
for (int j = 1; j <= i; j++) {
if (dp1[j][i] == 1) dp2[i] = Math.min(dp2[i], 1 + dp2[j - 1]);
}
}
}

return dp2[len - 1];
}
}


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