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.

class Solution {

public:

    int minCut(string s) {

        if(s.empty())return 0;

        int n=s.length();

        bool **T=new bool*[n];

        for(int i=0;i<n;i++)

        {

            T[i]=new bool[n];

            for(int j=0;j<n;j++)

            T[i][j]=false;

        }

        int *cut=new int[n+1];

        cut[n]=0;

        for(int i=n-1;i>=0;i--)

        {

            cut[i]=n-i;

            for(int j=i;j<n;j++)

            {

                if(s[i]==s[j]&&(i==j||i+1==j||T[i+1][j-1]))

                {

                    T[i][j]=true;

                    cut[i]=cut[i]<1+cut[j+1]?cut[i]:1+cut[j+1];

                }

            }

        }

        return cut[0]-1;

    }



/**

void judge(string s,bool ** &T)

{

    if(s.empty())return;

    for(int i=0;i<s.length();i++)

    {

        T[i][i]=true;

        int left=i-1,right=i;

        while(left>=0&&right<s.length()&&s[left]==s[right])

        {

            T[left--][right++]=true;

        }

        left=i-1,right=i+1;

        while(left>=0&&right<s.length()&&s[left]==s[right])

        {

            T[left--][right++]=true;

        }

    }

}

    int minCut(string s) {

        if(s.empty())return 0;

        int n=s.length();

        bool **T=new bool*[n];

        for(int i=0;i<n;i++)

        {

            T[i]=new bool[n];

            for(int j=0;j<n;j++)

            T[i][j]=false;

        }

        judge(s,T);

        int *cut=new int[n+1];

        cut[n]=0;

        for(int i=n-1;i>=0;i--)

        {

            cut[i]=n-i;

            for(int j=i;j<n;j++)

            {

                if(T[i][j])

                {

                    cut[i]=cut[i]<1+cut[j+1]?cut[i]:1+cut[j+1];

                }

            }

        }

        return cut[0]-1;

    }

*/

};

 

你可能感兴趣的:(partition)