[LeetCode] Palindrome Partitioning

本文介绍了一种字符串回文分区的算法实现,通过递归深度优先搜索的方式寻找所有可能的回文子串组合,并提供了C++代码示例。

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

[Problem]

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"]
  ]

[Analysis]

最简单的方法,直接深搜。更好一点的方法,用mark[i][j]记录s[i:j]是不是回文,然后再深搜。

[Solution]

class Solution {
public:
// is the string a palindrome
bool isPalindrome(string s){
// string with one letter
if(s.length() <= 1){
return true;
}

// check
int i = 0, j = s.length() - 1;
while(i <= j){
if(s[i] != s[j]){
return false;
}
i++;
j--;
}
return true;
}

// partition
vector<vector<string> > partition(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function

vector<vector<string> > res;

// empty string
if(s.length() == 0){
return res;
}
// string with one letter
else if(s.length() == 1){
vector<string> tmp;
tmp.push_back(s);
res.push_back(tmp);
}
// DFS
else{
// the length of the first part could be range from 0 to s.length()
for(int i = 1; i <= s.length(); ++i){
// get the first part
string head = s.substr(0, i);

// the first part is not a palindrome, continue
if(!isPalindrome(head))continue;

if(i == s.length()){
vector<string> tmp;
tmp.push_back(head);
res.push_back(tmp);
}
// generate the remained parts
else{
vector<vector<string> > r = partition(s.substr(i, s.length() - i));
for(int j = 0; j < r.size(); ++j){
r[j].insert(r[j].begin(), head);
res.push_back(r[j]);
}
}
}
}
return res;
}
};


 说明:版权所有,转载请注明出处。 Coder007的博客
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值