Leetcode 132. 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.

 

思路:用O(n^2)的复杂度预处理出来所有的回文串,注意边界情况。

         然后简单DP。

AC代码:

class Solution {
public:
    int minCut(string s) {
        int n = s.length();
        if(n == 0) return 0;
        vector<bool> temp(n, false);
        vector< vector<bool> > isPalindrome(n, temp);
        for(int i=0; i<n; i++)
        {
            for(int step=0; step<n; step++)
            {
                int left =  i - step;
                int right = i + step;
                if(left < 0 || right >= n) break;
                if(s[left] == s[right])
                    isPalindrome[left][right] = true;
                else break;
            }
            for(int step=1; step<n; step++)
            {
                int left =  i - step+1;
                int right = i + step;
                if(left < 0 || right >= n) break;
                if(s[left] == s[right])
                    isPalindrome[left][right] = true;
                else break;
            }
        }

        vector<int>dp(n, 1<<29);
        for(int i=0; i<n; i++)
        {
            if(isPalindrome[0][i]) dp[i] = 1;
        }

        for(int i=0; i<n-1; i++)
        {
            for(int j=i+1; j<n; j++)
            {
                if(isPalindrome[i+1][j])
                {
                    dp[j] = min(dp[j], dp[i]+1);
                }
            }
        }
        return dp[n-1] - 1;
    }
};
View Code

 

posted @ 2016-07-12 15:10  Gu Feiyang  阅读(133)  评论(0)    收藏  举报