LeetCode 131. 分割回文串

主页有其他数据结构内容(持续更新中)

难度:Medium

代码:

class Solution {
private:
    vector<vector<string>> result;
    vector<string> path;
    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;
    }
    //  回溯问题都可以抽象为一棵树形结构,通过for循环进行横向遍历,通过递归进行纵向遍历
    //  startIndex相当于一条切割线,代表下一轮递归遍历的起始位置
    void dfs(string s, int startIndex) {
        if(startIndex >= s.size()) {
            result.emplace_back(path);
            return;
        }
        //  for循环遍历的是从startIndex开始,到s.size()-1结束的位置
        for(int k = startIndex; k < s.size(); k++) {
            //  从startIndex到k位置能构成回文串
            if(isPalindrome(s, startIndex, k)) {
                string temp = s.substr(startIndex, k - startIndex + 1);
                path.emplace_back(temp);
                //  由于当前已经找到了从startIndex到k的回文串,因此需要继续寻找以k+1为起点的回文串
                dfs(s, k + 1);
                //  回溯,将当前插入的string弹出
                path.pop_back();
            }
            //  不是回文串,跳过
            else {
                continue;
            }
        }
    }
public:
    vector<vector<string>> partition(string s) {
        dfs(s, 0);
        return result;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值