Palindrome Partitioning II
30:00
Given a string s, cut s into some substrings such that every substring is a palindrome.
Return the minimum cuts needed for a palindrome partitioning of s.
Given s = "aab"
,
Return 1
since the palindrome partitioning ["aa", "b"] could be produced using 1 cut.
class Solution {
private:
int _min(int a, int b)
{
if (a <= b)
return a;
return b;
}
public:
/**
* @param s a string
* @return an integer
*/
int minCut(string s) {
// write your code here
int len = s.size();
vector<int> dp(len+1);
vector<vector<bool>> isPa(len, vector<bool>(len));
dp[0] = -1;
for (int i=0; i<len; i++)
{
dp[i+1] = i;
}
for (int i=0; i<len; i++)
for (int j=0; j<len; j++)
isPa[i][j] = false;
for (int i=0; i<len; i++)
isPa[i][i] = true;
for (int i=1; i<len; i++)
{
for (int j=i; j>=0; j--)
{
if ((s[i] == s[j]) && (i-j<2 || isPa[j+1][i-1]))
{
isPa[j][i] = true;
dp[i+1] = _min(dp[i+1], dp[j]+1);
}
else
{
dp[i+1] = _min(dp[j+1]+(i-j), dp[i+1]);
}
}
}
return dp[len];
}
};