leetcode: Palindrome Partitioning II解法

题目如下:

Given a string s, partition s such thatevery substring of the partition is a palindrome.

Return the minimum cuts needed for apalindrome partitioning of s.

For example, given s = "aab",
Return 
1 since thepalindrome partitioning ["aa","b"] could be produced using 1 cut.

这个题目的解法是动态规划。首先用b这个矩阵来代表s[i]-s[j]是否是palindrome。b[i][j]==true 意思是s[i]到s[j]事palindrome。 

之后用result来动态计算s[0]-s[j]的最小cut,每一次看判断最小值。

class Solution {
public:
    int minCut(string s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
         int len=s.length();
        if(len<1) return 0;
        
        vector<bool> temp(len,false);
        vector<vector<bool>> b(len,temp);
        
        int i;
        
        for(i=0;i<len;i++)
        {
            b[i][i]=true;
        }
        
        for(i=0;i<len-1;i++)
        {
            if(s[i]==s[i+1])
            b[i][i+1]=true;
        }
        
        int l;
        for(l=3;l<=len;l++)
        {
            for(i=0;i<=len-l;i++)
            {
                int j=i+l-1;
                if(s[i]==s[j] && b[i+1][j-1])
                b[i][j]=true;
                
            }
        }
        
        int min=helper(b,s);
        return min;
    }
    
    int helper(vector<vector<bool>>& b, string s)
    {
        vector<int> result(s.length(),0);
        result[0]=0;
        
        for(int j=0; j<s.length(); j++)
        {
            int min=j;
            if(b[0][j]) result[j]=0;
            else
            {
                for(int i=1;i<=j;i++)
                {
                    if(b[i][j] && result[i-1]+1<=min)
                    min=result[i-1]+1;
                }
                result[j]=min;   
            }
        }
        return result[s.length()-1];
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值