您的位置:首页 > 编程语言 > Java开发

palindrome-partitioning Java code

2017-10-20 11:32 447 查看
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”,

Return1since the palindrome partitioning[“aa”,”b”]could be produced using 1 cut.

public class Solution {
public int minCut(String s) {
if (s == null || s.length() <= 1){
return 0;
}
int n = s.length();
int i;
int j;
int[] minCut = new int[n + 1];
for (i = 0; i < n + 1; i++){
minCut[i] = i - 1;
}
for(i = 1; i < n; i++){
// odd-length
for (j = 0; i - j >= 0 && i + j < n && s.charAt(i - j) == s.charAt(i + j); j++){
minCut[i + j + 1] = Math.min(minCut[i + j + 1], minCut[i - j] + 1);
}
// even-length
for (j = 0; i - j - 1 >= 0 && i + j < n && s.charAt(i - j - 1) == s.charAt(i + j); j++){
minCut[i + j + 1] = Math.min(minCut[i + j + 1], minCut[i - j - 1] + 1);
}
}
return minCut
;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息