leetcode 123: Palindrome Partitioning II

Palindrome Partitioning II Mar 1

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.


class Solution {
public:
    int minCut(string s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int sz = s.length();
        if(sz<1)return 0;
        
        vector<bool> temp(sz, false);
        vector<vector<bool>> b(sz, temp);
        
        for(int i=0; i<sz; i++) {
            b[i][i] = true;
        }
        
        for(int i=0; i<sz-1; i++) {
            if(s[i]==s[i+1]) {
                b[i][i+1] = true;
            }
        }
        
        for(int len=3; len<=sz; len++) {
            for(int i=0; i<=sz-len; i++) {
                int j=i+len-1;
                if(s[i]==s[j] && b[i+1][j-1]) {
                    b[i][j] = true;
                }
            }
        } 
        
        vector<int> d(sz, 0);
        for(int i=0; i<sz; i++) {
            if( b[0][i]) {
                d[i]==0;
                continue;
            }
            int min = INT_MAX;
            for(int k=1; k<=i; k++) {
                if(b[k][i]) {
                    int x = d[k-1] + 1;
                    min = min<x ? min : x;
                }
            }
            d[i] = min;
        }        
        return d[sz-1];
    }
};


你可能感兴趣的:(leetcode 123: Palindrome Partitioning II)