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 ofs.

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

       首先,遍历s,求出所有的回文,存放在二维数组中,对于flag[i][j],如果s[i..j]为回文,则flag[i][j]=1,否则flag[i][j]=0;

       然后,对于最小的剪切次数,可以通过DP思想,从s[0]开始往s[s.length()-1],求最小的剪切次数f[0]...f[s.length()-1]。

       时间复杂度为O(n^2)。

       备注:对于a+b=c?1:2,与a+(b=c?1:2)是不相同的!

class Solution {
public:
    vector<vector<int> > flag;
    void buildFlag(string s){
        vector<int> temp;
        for(int i=0;i<s.length();i++)temp.push_back(0);
        for(int i=0;i<s.length();i++)flag.push_back(temp);
        for(int i=0;i<s.length();i++){
            int tempi=i,tempj=i;
            while(tempi>=0&&tempj<s.length()&&s[tempi]==s[tempj]){flag[tempi][tempj]=1;tempi--;tempj++;}
            tempi=i;tempj=i+1;
            while(tempi>=0&&tempj<s.length()&&s[tempi]==s[tempj]){flag[tempi][tempj]=1;tempi--;tempj++;}
        }
    }
    int minCut(string s) {
        if(s.length()<=1)return 0;
        buildFlag(s);
        int *f = new int[s.length()];
        f[0]=0;
        for(int i=1;i<s.length();i++){
            f[i]=f[i-1]+1;
            if(flag[0][i])f[i]=0;
            else {
                for(int j=0;j<i;j++)
                f[i]=min(f[i],f[j]+(flag[j+1][i]==1?1:(i-j)));//如果用==?:,一定要注意运算符的优先级
            }
        }
        return f[s.length()-1];
    }
};

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值