[LeetCode] Palindrom Partitioning II

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) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        if(s.length()<=1) return 0;
        
        vector<vector<int>> pTable(s.length(),vector<int>(s.length(),0));
        for(int i=0;i<s.length();i++)
        {
            pTable[i][i]=1;
            if(i<s.length()-1)
                pTable[i][i+1]= (s[i]==s[i+1]);
        }
        
        for(int i=s.length()-2;i>=0;i--)
        {
            for(int j=i+2;j<s.length();j++)
            {
                pTable[i][j]= (s[i]==s[j]) && pTable[i+1][j-1];
            }
        }
        
        vector<int> Cuts(s.length()+1,INT_MAX);//the mininum number of cuts from i to the end
        Cuts[s.length()]=-1;
        for(int i=s.length()-1;i>=0;i--)
        {
            for(int j=i;j<s.length();j++)
            {
                if(pTable[i][j]==1)
                    Cuts[i]=min(Cuts[i],Cuts[j+1]+1);
            }
        }
        
        return Cuts[0];
    }
};


發佈了110 篇原創文章 · 獲贊 4 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章