leetcode练习 分割回文串

给你一个字符串 s,请你将s分割成一些子串,使每个子串都是

回文串

。返回 s 所有可能的分割方案。

示例 1:

复制代码
输入:s = "aab"
输出:[["a","a","b"],["aa","b"]]

示例 2:

复制代码
输入:s = "a"
输出:[["a"]]

提示:

  • 1 <= s.length <= 16
  • s 仅由小写英文字母组成

思路,我们可以采用回溯算法,找到每一个字符串的组合,再判断是否是回文串,在回溯函数中,我们采用一个for循环更新容器大小用来截取字符串长度。

cpp 复制代码
class Solution {
public:
    vector<vector<string>>res;
    vector<string>path;
    bool is_fun(int left,int right,string s){
        if(left>right)return false;
        while(left<right){
            if(s[left]!=s[right])return false;
            left++;
            right--;
        }
        return true;
    }
    void backtracing(int left,int right,string s){
        if(left>right){
            res.push_back(path);
            return ;
        }
        for(int i=0;i<right-left+1;i++){
            if(is_fun(left,left+i,s)){
                path.push_back(s.substr(left,i+1));
                backtracing(left+i+1,right,s);
                path.pop_back();
            }
        }
    }
    vector<vector<string>> partition(string s) {
        backtracing(0,s.size()-1,s);
        return res;
    }
};

给定字符串大小除去上面方法外,我们还可以使用substr函数,我认为这样写更加清晰,在判断是否是回文串时可以直接重新计算字符串的left和right,像上面函数中写的,在调用is_fun函数时,我第一次写时传错参数is_fun(left.i,s)导致开头传错判断错误。

cpp 复制代码
       for(int i=1;i<=right-left+1;i++){
            if(is_fun(s.substr(left,i))){
                path.push_back(s.substr(left,i));
                backtracing(left+i,right,s);
                path.pop_back();
            }
相关推荐
Savior`L5 小时前
二分算法及常见用法
数据结构·c++·算法
mmz12076 小时前
前缀和问题(c++)
c++·算法·图论
努力学算法的蒟蒻7 小时前
day27(12.7)——leetcode面试经典150
算法·leetcode·面试
甄心爱学习7 小时前
CSP认证 备考(python)
数据结构·python·算法·动态规划
kyle~8 小时前
排序---常用排序算法汇总
数据结构·算法·排序算法
AndrewHZ8 小时前
【遥感图像入门】DEM数据处理核心算法与Python实操指南
图像处理·python·算法·dem·高程数据·遥感图像·差值算法
CoderYanger8 小时前
动态规划算法-子序列问题(数组中不连续的一段):28.摆动序列
java·算法·leetcode·动态规划·1024程序员节
有时间要学习8 小时前
面试150——第二周
数据结构·算法·leetcode
liu****9 小时前
3.链表讲解
c语言·开发语言·数据结构·算法·链表