LeetCode132:Palindrome 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.

解题思路:

这题是参考网上大牛的,一开始我采用上一题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("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa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