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.
Subscribe to see which companies asked this question
class Solution {
public:
int minCut(string s) {
vector<vector<bool>> dp(s.size(), vector<bool>(s.size()));
for (int i=0; i<s.size(); i++)
dp[i][i] = true;
for (int i=1; i<s.size(); i++)
if (s[i-1] == s[i])
dp[i-1][i] = true;
for (int len=2; len<=s.size(); len++)
{
//这里等号要注意
for (int i=0; i<=(int)s.size()-1-len; i++)
{
if (s[i] == s[i+len] && dp[i+1][i+len-1])
dp[i][i+len] = true;
}
}
vector<int> auxDP(s.size()+1);
auxDP[s.size()] = -1; //这里的初始化为-1 也要注意
for (int i=s.size()-1; i>=0; i--)
{
auxDP[i] = INT_MAX;//这里要先赋值
for (int j=i; j<s.size(); j++)
{
if (dp[i][j])
{
auxDP[i] = min(auxDP[i], auxDP[j+1]+1);
}
}
}
return auxDP[0];
}
};