您的位置:首页 > 其它

Leetcode-Palindrome Partitioning II

2014-12-12 04:15 411 查看
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.

Analysis:

DP

Solution:

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

int[] minCut = new int[s.length()+1];
minCut[0] = -1;
boolean[][] valid = new boolean[s.length()][s.length()];
for (int i=0;i<s.length();i++){
valid[i][i]=true;
}

for (int i=1;i<=s.length();i++){
minCut[i] = minCut[i-1]+1;
for (int j=i-2;j>=0;j--)
if (s.charAt(j)==s.charAt(i-1) && (j==i-2 || valid[j+1][i-2])){
valid[j][i-1]=true;
minCut[i] = Math.min(minCut[i],minCut[j]+1);
}

}

return minCut[s.length()];
}

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