Palindrome Partitioning

题目大意:给定一个字符串,要求你对其进行切割,保证切割后每个子字符串都是回文串,要你求所有满足条件的集合

解题思路:递归,为了避免重复计算,用isPalindrome[i][j]表示str[i][j]是否是回文串,为0表示不是,1表示是,-1表示还没有遍历进行判断


class Solution {
public:
    vector<vector<string>> partition(string s) {
        vector<vector<string> > result;
        if(s.empty()) {
            return result;
        }
        vector<vector<int> > isPalindrome(s.size(), vector<int>(s.size(), -1));
        vector<string> strs;
        for(int i = 0; i < s.size(); i++) {
            isPalindrome[i][i] = 1;
        }
        partitionAssist(s, 0, result, strs, isPalindrome);
        return result;
    }
private:
    void partitionAssist(const string &s, int startIndex, vector<vector<string> > &result, vector<string> &strs, vector<vector<int> > &isPalindrome) {
        if(startIndex >= s.size()) {
            if(!strs.empty()) {
                result.push_back(strs);
            }
        }

        for(int len = 1; startIndex + len <= s.size(); len++) {
            if(isPalindrome[startIndex][startIndex + len - 1] == 0) {
                continue;
            } else if(isPalindrome[startIndex][startIndex + len - 1] == 1) {
                strs.push_back(s.substr(startIndex, len));
                partitionAssist(s, startIndex + len, result, strs, isPalindrome);
                strs.pop_back();
            } else {
                if(s[startIndex] == s[startIndex + len - 1] && (len == 2 || isPalindrome[startIndex + 1][startIndex + len - 2] == 1)) {
                    isPalindrome[startIndex][startIndex + len - 1] = 1;
                    strs.push_back(s.substr(startIndex, len));
                    partitionAssist(s, startIndex + len, result, strs, isPalindrome);
                    strs.pop_back();
                } else {
                    isPalindrome[startIndex][startIndex + len - 1] = 0;
                }
            }
        }
    }
};




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值