Friday, April 17, 2015

[LeetCode] 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.
class Solution {
public:
    int minCut(string s) {
        int len = s.length();
        bool P[len][len];
        int C[len];
        for(int i=0;i<len;i++)
        {
            C[i] = len - i - 1;
            for(int j=0;j<len;j++) 
            {
                P[i][j] = false;
            }
        }
        
        for(int i=len-1;i>=0;i--)
        {
            for(int j=i;j<len;j++)
            {
                if(s[i] == s[j] && (j-i<2 || P[i+1][j-1]))
                {
                    P[i][j] = true;
                    if(j == len-1) C[i] = 0;
                    else C[i] = min(C[i], C[j+1] + 1);
                }
            }
        }
        return C[0] ;
    }
};