[LintCode] Palindrome Partitioning II

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];
    }
};

 

posted @ 2015-10-09 10:25  xchangcheng  阅读(109)  评论(0编辑  收藏  举报