[ 回溯 ] 分割回文串

131. 分割回文串 - 力扣(LeetCode) (leetcode-cn.com)

分割回文串

  • 与数组组合不同的是,数组是取数,该题是找分割线
class Solution {
public:
    // 返回值
    vector<vector<string>> ans;
    vector<string> path;
    
    // DFS
    void DFS(string& s, int index) {
        // 边界
        if (index >= s.size()) {
            ans.emplace_back(path);
            return;
        }
        for (int i = index; i < s.size(); ++i) {
            // 数组是找到一个数,就进入下一层
            // 而字符串是必须找到一个回文串,才能继续下一层分割,所以才有continue语句
            if (isPalindrome(s, index, i)) {
                string str = s.substr(index, i - index + 1);
                path.emplace_back(str);
            }
            else {
                continue;
            }
            DFS(s, i + 1);
            path.pop_back();
        }
    }
	
    // 判断回文串
    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) {
        DFS(s, 0);
        return ans;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值