首页 > 其他 > 详细

[LintCode] Palindrome Partitioning II

时间:2015-10-09 11:38:11      阅读:247      评论:0      收藏:0      [点我收藏+]

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.

 
Example

For example, given s = "aab",

Return 1 since the palindrome partitioning ["aa","b"] could be produced using 1 cut.

 

Sol:

class Solution {
public:
    /**
     * @param s a string
     * @return an integer
     */
    int minCut(string s) {
         int n = s.size();
        vector<vector<bool> > isPalin(n, vector<bool>(n, false));
        vector<int> min_cut(n, -1); //min cut to end
        
        for(int i = 0;i < n;++i)
            isPalin[i][i] = true;
        
        min_cut[0] = 0;
        for(int i = 1;i < n;++i){
            min_cut[i] = min_cut[i - 1] + 1;
            for(int j = 0;j < i;++j){
                if(s[j] == s[i]){
                    if(j + 1 == i || isPalin[j + 1][i - 1]){
                        isPalin[j][i] = true;
                        if(j > 0) min_cut[i] = min(min_cut[i], min_cut[j - 1] + 1);
                        else min_cut[i] = 0;
                    }
                }
            }
        }
        
        return min_cut[n - 1];
    }
};

 

[LintCode] Palindrome Partitioning II

原文:http://www.cnblogs.com/changchengxiao/p/4863141.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!