95:Palindrome Partitioning

本文介绍了一种使用动态规划解决回文字符串划分问题的方法。该算法不仅能够判断给定字符串的各子串是否为回文,同时还能找出所有可能的回文子串组合。对于长度为n的输入字符串,时间复杂度为O(n^2),空间复杂度也为O(n^2)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
For example, given s = “aab”, Return
[
[“aa”,”b”],
[“a”,”a”,”b”]
]
代码如下:

// 动态规划,时间复杂度 O(n^2),空间复杂度 O(n^2)
// 不仅判断 s 的各个子字符串s[i, j] 是否为回文
// 同时还给出 s 的所有回文字段
class Solution {
public:
        vector<vector<string>> partition(string s) {
                const int n = s.size();
                bool table[n][n] = { true }; // s[i, j] 是否为回文

                // sub_palins[i] 表示子字符串 s[i, n) 中的一段段回文
                vector<vector<string>> sub_palins[n];

                for (int i = n - 1; i >= 0; --i)
                        for (int j = i; j <= n - 1; ++j) {
                                int l = j - i + 1;
                                if (l == 1) table[i][j] = true;
                                else if (l == 2) table[i][j] = s[i] == s[j];
                                else table[i][j] = table[i + 1][j - 1] && (s[i] == s[j]);

                                if (table[i][j]) {
                                        const string palindrome = s.substr(i, j - i + 1);
                                        if (j == n - 1) sub_plains[i].push_back(vector<string>{palindrome});
                                        else {
                                                for (auto v : sub_palins[j + 1]) {
                                                        v.insert(v.begin(), palindrome);
                                                        sub_palins[i].push_back(v);
                                                }
                                        }
                                }
                        }
                return sub_palins[0];
        }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值