题目:
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.
思路|代码:
class Solution {
public:
int minCut(string s) {
//cut[i] = the minimum of cut[j - 1] + 1 if [j, i] is palindrome
//if s[i] == s[j], [j + 1, i - 1] is palindrome, [j, i] is palindrome
int n = s.size();
vector<vector<bool>> pal(n, vector<bool>(n, false));
vector<int> cut(n, INT_MAX);
for(int i = 0; i < n; i++)
{
int tmin = i;
for(int j = 0; j <= i; j++)
{
if(s[i] == s[j] && (j + 1 > i - 1 || pal[i - 1][j + 1]) )
{
pal[i][j] = true;
tmin = j == 0? 0 : min(tmin, cut[j - 1] + 1);
}
}
cut[i] = tmin;
}
return cut[n - 1];
}
};