码迷,mamicode.com
首页 > 其他好文 > 详细

Palindrome Partitioning II

时间:2014-05-30 15:13:10      阅读:262      评论:0      收藏:0      [点我收藏+]

标签:c   style   class   blog   code   java   

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.

bubuko.com,布布扣
class Solution {
public:
    int minCut(string s) 
    {     
        int n=s.length();        
        
        int* pali1=new int[n+1];
        int* pali2=new int[n+1];
        //1  3 5
        for(int i=0;i<n;i++) pali1[i]=1;
        for(int len=3;len<=n;len=len+2)
            for(int l=len/2;l<=n-1-len/2;l++)
                if(pali1[l]==len-2 && s[l-len/2]==s[l+len/2])
                    pali1[l]=len;
        //0 2 4
        for(int i=0;i<n;i++) pali2[i]=0;
        for(int len=2;len<=n;len=len+2)
            for(int l=len/2-1;l<=n-1-len/2;l++)
                if(pali2[l]==len-2 && s[l+1-len/2]==s[l+len/2])
                    pali2[l]=len;
        int** cutcache=new int*[n];
        for(int i=0;i<n;i++)
        {
            cutcache[i]=new int[n];
            for(int j=0;j<n;j++) cutcache[i][j]=-1;
        }
        return mincut(cutcache,s,0,n-1,pali1,pali2);
    }
    int mincut(int** cutcache,const string& s,int l,int r,const int* pali1,const int* pali2)
    {
        if(cutcache[l][r]!=-1) return cutcache[l][r];
        if(l>=r) return 0;
        
        if(check(s,l,r,pali1,pali2)) 
        {
            cutcache[l][r]=0;
            return 0;
        }
        int cut=r-l+1;
        for(int i=l;i<r;i++)
        if(check(s,l,i,pali1,pali2))
        {
            int newcut=1+mincut(cutcache,s,i+1,r,pali1,pali2);
            if(newcut<cut) cut=newcut;
        }
        cutcache[l][r]=cut;
        
        return cut;
    }
    bool check(const string& s,int l,int r,const int* pali1,const int* pali2)
    {
        int len=r-l+1;
        int mid=(l+r)/2;
        if(len%2==1 && pali1[mid]>=len) return true;
        if(len%2==0 && pali2[mid]>=len) return true;
        return false;
    }
};
bubuko.com,布布扣

 

Palindrome Partitioning II,布布扣,bubuko.com

Palindrome Partitioning II

标签:c   style   class   blog   code   java   

原文地址:http://www.cnblogs.com/erictanghu/p/3759691.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!