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 n = s.length();
        if (n < 1)
        {
            return 0;
        }

        bool isPal[n][n];//记录从i到j之间的字符串是否为回文
        memset(isPal, false, n*n*sizeof(bool));
        int cut[n];//记录从0到i的字符串的最小切割数量
        cut[0] = 0;

        for (int i = 1; i < n; i++)
        {
            cut[i] = cut[i-1] + 1;
            for (int j = 0; j <= i; j++)
            {
                if (s[i] == s[j] && (i-j < 2 || isPal[j+1][i-1]))
                {
                    isPal[j][i] = true;
                    if (j == 0)
                    {
                        cut[i] = 0;
                    }
                    else if (cut[j-1]+1 < cut[i])
                    {
                        cut[i] = cut[j-1] + 1;
                    }
                }
            }
        }

        return cut[n-1];
    }
};


你可能感兴趣的:(Palindrome Partitioning II)