LeetCode132:Palindrome Partitioning II

mickole發表於2014-04-24

題目:

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.

解題思路:

這題是參考網上大牛的,一開始我採用上一題Palindrome Partitioning解題思路,結果執行超時。

實現程式碼:

#include <iostream>
#include <vector>
#include <iterator>
#include <unordered_map>
#include <string>
#include <algorithm>

using namespace std;
/*
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:
    //DP
     /*
     如果if s[j...k] 為迴文串,則 dp[k] = min{ dp[k], dp[j - 1] + 1}  0 <=j <= k - 1;
     否則 dp[k] = dp[k - 1] + 1
   */
    int minCut(string s){
        if(s.size() == 0)
            return -1;
            //dp儲存前i個字串最小切割數 
        vector<int> dp(s.size() + 1, s.size()-1);//初始化最小切分數為s.size-1 

        //儲存i—j是否為迴文串 
        vector<vector<bool> > status(s.size(), vector<bool>(s.size(), false));
        dp[0] = -1;
        for(int i = 0; i < s.size(); ++i)
        {
           
            dp[i + 1] = dp[i] + 1;//假定,s[i]不能和其前面的字串構成迴文串,則s[i]為單獨迴文串即要切分 
            /*
            檢查s[i]能否和其前面的字串構成迴文串,如果可以,則更新dp[i+1] 
            */ 
            for(int cur = i - 1; cur >= 0; --cur)
                if(s[i] == s[cur] && (i - cur <= 2 || status[cur + 1][i - 1])){
                    dp[i + 1] = min(dp[i + 1], dp[cur] + 1);
                    status[cur][i] = true;
                }
            
        }
        return dp[s.size()];
    }
    
    
};

int main(void)
{
    string s("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa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