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.
Leetcode上不用双重dp的解法:https://oj.leetcode.com/discuss/9476/solution-does-not-need-table-palindrome-right-uses-only-space
1.双重DP
a. 首先建立一个palindrome查询表如下,表示从j到i的字符串是否为palindrome:(i-> row, j-> col)
a | a | b | |
a | true | ||
a | true | true | |
b | false | false | true |
c. 注意最后返回c[s.length()]-1。因为c[i]代表了第i-1位最少的palindrome个数,cut数= 个数-1.
public int minCut(String s) {
boolean[][] dict = new boolean[s.length()][s.length()];
for (int i = 0; i < s.length(); i++) {
for (int j = i; j >= 0; j--) {
if ((i-j < 2 || dict[i-1][j+1]) && s.charAt(i) == s.charAt(j)) {
dict[i][j] = true;
}
}
}
int[] cut = new int[s.length()+1];
cut[0] = 0;
for (int i = 0; i < s.length(); i++) {
cut[i+1] = i+1;
for (int j = 0; j <= i; j++) {
if (dict[i][j]) {
cut[i+1] = Math.min(cut[i+1], cut[j]+1);
}
}
}
return cut[s.length()]-1;
}
2. 和palindrome partitioningI 一样的做法,维护一个最小值,输入为ababababababababababababcbabababababababababababa超时。
public class Solution {
int min;
public int minCut(String s) {
min = Integer.MAX_VALUE;
helper(s, 0);
return min < 0 ? 0 : min;
}
void helper(String s, int cut) {
if (s.isEmpty()) {
if (cut-1 < min) {
min = cut-1;
}
}
for (int i = 1; i <= s.length(); i++) {
if (isPalindrome(s.substring(0, i))) {
helper(s.substring(i), cut+1);
}
}
}
boolean isPalindrome (String s) {
int n = s.length();
for (int i = 0, j = n-1; i < j; i++, j--) {
if (s.charAt(i) != s.charAt(j)) {
return false;
}
}
return true;
}
}