LeetCode 131. Palindrome Partitioning

Given a string s, partition s such that every substring of the partition is a palindrome.

Return all possible palindrome partitioning of s.

Example:

Input: “aab”
Output:
[
[“aa”,“b”],
[“a”,“a”,“b”]
]

题目链接

可以回溯法切割出来字串,然后判断是否为回文串

由于要找出来全部的字串,所有回溯的范围应该是全部遍历一遍。使用for循环进行横向的遍历,for循环结束的条件就是本层集合的个数(也就是树中孩子的数量),cur代表当前要切割的位置

for(int i=cur;i<s.length();i++)

然后进行纵向的遍历,每当切割出来一个回文串,就把其放入tmp中,然后进行回溯。否则跳过。

if(Ispalindrome(s,cur,i)){
                string item=s.substr(cur,i-cur+1);
                tmp.push_back(item);
                dfs(s,i+1);
                tmp.pop_back();
            }else{
                continue;
            }

回溯结束的条件就是当切割点cur的大小已经大于或者等于s的大小

if(cur>=s.length())

判断回文串较为简单,用两个指针分别指向字符串的头和尾,如果两个指针所指向的字母一直相等到中间,就是回文串。

bool Ispalindrome(string s,int start,int end){
        for(int i=start,j=end;i<j;i++,j--){
            if(s[i]!=s[j]){
                return false;
            }
        }
        return true;
    }

全部代码如下:

class Solution {
public:
    vector<vector<string>> res;
    vector<string> tmp;
    
    void dfs(const string &s,int cur){
        if(cur>=s.length()){
            res.push_back(tmp);
            return;
        }
        for(int i=cur;i<s.length();i++){
            if(Ispalindrome(s,cur,i)){
                string item=s.substr(cur,i-cur+1);
                tmp.push_back(item);
                dfs(s,i+1);
                tmp.pop_back();
            }else{
                continue;
            }
           
        }


    }
    bool Ispalindrome(string s,int start,int end){
        for(int i=start,j=end;i<j;i++,j--){
            if(s[i]!=s[j]){
                return false;
            }
        }
        return true;
    }
    vector<vector<string>> partition(string s) {
        tmp.clear();
        res.clear();
        dfs(s,0);
        return res;
    }
};
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Otto_1027

蟹蟹你,我会继续努力的~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值