码迷,mamicode.com
首页 > 其他好文 > 详细

132. Palindrome Partitioning II (String; DP)

时间:2015-10-23 21:36:16      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:

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.

思路: 除了用flag[i][j]记录从i到j是否是Palindrome,还要用cut[i]存储到i位置位置最少的cut数

class Solution {
public:
    int minCut(string s) {
        int sLength = s.length();
        vector<vector<bool>> flag(sLength,vector<bool>(sLength, false));
        int cut[sLength];
        cut[0]=0;
        
        for (int i=1;i<sLength;i++)
        {
            cut[i]=1+cut[i-1];
            for(int j=0;j<i;j++)
                if(s[i]==s[j]&&(i-j<=2||flag[j+1][i-1]))
                {
                    flag[j][i]=true;
                    if(j==0) 
                    {
                        cut[i] = 0;
                        break;
                    }
                    else cut[i] = min(cut[i],1+cut[j-1]);
                }
        }
        return cut[sLength-1];
    }
};

 

132. Palindrome Partitioning II (String; DP)

标签:

原文地址:http://www.cnblogs.com/qionglouyuyu/p/4905676.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!