LeetCode: Palindrome Partitioning II [132]

來源:互聯網
上載者:User

標籤:leetcode   演算法   面試   

【題目】

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.


【題意】

    給定一個字串s, 返回最小切割次數,是的所有的切割子串都為迴文。


【思路】

    DP,依次確定s[1...n]的最小分割次數
    假設用minCuts[i]表示,以第i結尾的字串的最小切分次數。
    那麼怎麼確定minCuts[i]. 我們已知了minCuts[j] j=0,1,...,i-1
    對於i之前的每個位置j, 如果s[j+1,..,i]為迴文串,則j為切割點的最小切割次數就是minCuts[j]+1;
    所以我們要從所有的j中取一個位置使得i位置的切割次數最小的位置作為切割點,即minCuts[i]=min{minCuts[j]+1} s[j+1,..,i]是迴文,j=0,1...i-1

    


【代碼】
class Solution {public:    int minCut(string s) {        int len=s.length();        if(len==0||len==1)return 0;        //構造迴文判別矩陣        vector<vector<bool> > isPal(len, vector<bool>(len, false));        //初始化isPal[i][i]        for(int i=0; i<len; i++)            isPal[i][i]=true;        //初始化isPal[i][i+1]        for(int i=0; i<len-1; i++)            if(s[i]==s[i+1])isPal[i][i+1]=true;        //初始化其他i<j的子串        for(int i=len-3; i>=0; i--)            for(int j=i+2; j<len; j++)                isPal[i][j]=(s[i]==s[j])&&isPal[i+1][j-1];                        //求最小切割        vector<int> minCuts(len, 0);  //記錄以i結尾的子串的最小切分數        for(int i=0; i<len; i++){            int mincut=INT_MAX;            for(int j=-1; j<i; j++){                if(isPal[j+1][i]){                    if(j==-1)mincut=0;                    else if(minCuts[j]+1<mincut)mincut=minCuts[j]+1;                }            }            if(mincut!=INT_MAX)minCuts[i]=mincut;        }        return minCuts[len-1];    }};


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.