题目: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.
解析*:该题目的解法思路和 Palindrome Partitioning 几乎一模一样,在依据动态规划算法判断字符串 s 的各个子字符串 s[i, j] 是否为回文的同时,给出最小切割数,代码如下:
// 动态规划,时间复杂度 O(n^2),空间复杂度 O(n^2)
// 不仅判断字符串s 的各个子字符串s[i, j] 是否为回文,
// 同时在此过程中还求出字符串 s 的回文最小切割数
// 代码更为紧凑,简洁
class Solution {
public:
int minCut(string s) {
const int n = s.size();
bool table[n][n] = {true}; // 判断 s[i,j] 是否为回文
// min[i] 表示子字符串s[i, n)的最小回文切割数
int min[n + 1];
for (int i = 0; i <= n; ++i)
min[i] = n - i - 1; // 最后一个 min[n] = -1;
for (int i = n - 1; i >= 0; --i) {
for (int j = i; j < n; ++j) {
int len = j - i + 1;
if (len == 1) table[i][j] = true;
else if (len = 2) table[i][j] = s[i] == s[j];
else table[i][j] = table[i + 1][j - 1] && s[i] == s[j];
min[i] = table[i][j] ? min(min[i], min[j + 1] + 1) : min[i];
}
}
return min[0];
}
};