*leetcode #132 in cpp

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.


Code:

class Solution {
public:
    int minCut(string s) {
       int n = s.length();
        if(s.empty()) return 0; 
        vector<vector<bool>> isPal(n,vector<bool>(n,false));
        for(int i = 0; i < n; i ++){
            isPal[i][i] = true;
            for(int j = 0; j < i; j ++){
                if( j== i -1){
                    isPal[j][i] = s[i]==s[j];
                }else{
                    isPal[j][i] = isPal[j+1][i-1] && s[j] == s[i]; 
                }
            }
        }
        
        if(isPal[0][n-1]) return 0;
        
        vector<int> dp(n,n);//dp[i] = min cut in s[0...i]
        for(int i = 0; i < n; i ++){
            dp[i] = i;//worst case, s[0...i] has i cuts
            if(isPal[0][i]) dp[i] = 0; 
            else{
                int j = 0; 
                while(j<i){
                    if(isPal[j+1][i]) dp[i] = min(dp[i], dp[j] + 1);
                    j++;
                }
            }
            
        }
        return dp[n-1];
    }
    
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章