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 of s.

For example, given s = "aab",

Return 1 since the palindrome partitioning ["aa","b"] could be produced using 1 cut.

这题卡时间卡的很严,自认为N^2的算法还是超时

1.

class Solution {
public:
    int minCut(string s) {
        int l = s.length();
        if(l <= 1) return 0;
        P = vector<vector<bool> > (l, vector<bool> (l, false));
        for(int i = 0; i < l; ++i){
            P[i][i] = true;
            if(i + 1 < l){
                P[i][i + 1] = (s[i] == s[i + 1]);
            }
        }
        for(int k = 2; k < l; ++k)
        for(int i = 0; i + k < l; ++i)  {
            P[i][i + k] = (s[i] == s[i + k]) && P[i + 1][i + k -1];
        }

        vector<int> F(l, l - 1);
        F[0] = 0;
        for(int i = 1; i < l; ++i){
            if(P[0][i]){
                F[i] = 0;
                continue;
            }
            for(int j = 1; j <= i; ++j){
                if(P[j][i]){
                    F[i] = min(F[i], F[j - 1] + 1);
                }
            }
        }
        return F[l - 1];
    }
private:
    vector<vector<bool> > P;
};

2.可以离散化成每一个回文词判断一次,就过了

class Solution {
public:
    int minCut(string s) {
        int l = s.length();
        if(l <= 1) return 0;
        P = vector<vector<bool> > (l, vector<bool> (l, false));
        vector<int> F(l, 0);
        for(int i = 0; i < l; ++i){
            F[i] = i;
        }
        for(int i = 0; i < l; ++i){
            for(int j = i; j >= 0; --j){
                if(s[i] == s[j] && (i - j < 2 || P[j + 1][i - 1])){
                    P[j][i] = true;
                    F[i] = min(F[i], j == 0 ? 0 : F[j - 1] + 1);
                }
            }
        }

        return F[l - 1];
    }
private:
    vector<vector<bool> > P;
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值