leetcode Palindrome Partitioning II

Palindrome Partitioning II

  Total Accepted: 14865  Total Submissions: 82333 My Submissions

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.

Have you been asked this question in an interview? 

Discuss

这道题目,对于O(n^2)求出所有的回文字串,必须用dp的方法。参考我前一篇文章 http://blog.csdn.net/nan327347465/article/details/39157263 

然后这篇文章,求出最小划分,需要用dp的思想,不然会超时。

/**
 * Use the dp thought, the dp store the infomation of minCut for dp[0]=0, for the one character is palindrome partitioning, and for
 * dp[1] if s[0]~s[1] is palindrome then the dp[1] is zero, otherwise dp[1] = dp[0]+1; For dp[2] if s[0]~s[2] is  palindrome then the
 * dp[2] = 0. However the thing is not that easy. If s[0]~s[2] is not palindrome, you should  set dp[2] be min(dp[0]+1,dp[1]+1)
 * respectively the condition is s[1]~s[2] is palindrome or s[2]~s[2] is palindrome.
 *  For the general dp function
 *  dp[i] = 0 if(s[0]~s[i] is palindrome) 
 *      or min (dp[j]+1) 0<j<i if(s[j+1]~s[i] is palindrome) 
 * 
 */

class Solution {
   public:
    int minCut(string s) {
        int i,j,len = s.size();
        vector<vector<bool> > palin(len,vector<bool>(len,false));
        vector<int> dp (len,0);
        // learn the initialization of a palin system.
        for(i=0;i<len;i++)
        {
            palin[i][i] = true;
            if(i<len-1&&s[i]==s[i+1])
            {
                palin[i][i+1] = true;
            }
        }
        for(i=2;i<len;i++)
        {
            for(j=0;j+i<len;j++)
            {
                if(s[j]==s[j+i]&&palin[j+1][j+i-1])
                {
                    palin[j][j+i] = true;
                }
            }
        }
        //来一个双重循环,考虑到其有可能在中间某部分是回文串,所以还要从前向后计算。
        for(i=0;i<len;i++)
        {
            if(palin[0][i])
            {
                dp[i] = 0;
            }else
            {
                int tmp = 99999999;
                for(j=0;j<i;j++)
                {
                    if(palin[j+1][i] && tmp>(dp[j]+1))
                    {
                        tmp = dp[j]+1;
                    }
                }
                dp[i] = tmp;
            }
        }
        return dp[len-1];
    }

};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值