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();
            }
相关推荐
米粒19 小时前
力扣算法刷题 Day 27
算法·leetcode·职场和发展
Fuxiao___10 小时前
C 语言核心知识点讲义(循环 + 函数篇)
算法·c#
Mr_Xuhhh10 小时前
LeetCode hot 100(C++版本)(上)
c++·leetcode·哈希算法
漫随流水11 小时前
c++编程:反转字符串(leetcode344)
数据结构·c++·算法
穿条秋裤到处跑12 小时前
每日一道leetcode(2026.03.31):字典序最小的生成字符串
算法·leetcode
CoovallyAIHub14 小时前
VisionClaw:智能眼镜 + Gemini + Agent,看一眼就能帮你搜、帮你发、帮你做
算法·架构·github
CoovallyAIHub14 小时前
低空安全刚需!西工大UAV-DETR反无人机小目标检测,参数减少40%,mAP50:95提升6.6个百分点
算法·架构·github
CoovallyAIHub14 小时前
IEEE Sensors | 湖南大学提出KGP-YOLO:先定位风电叶片再检测缺陷,三数据集mAP均超87%
算法
Yupureki15 小时前
《算法竞赛从入门到国奖》算法基础:动态规划-路径dp
数据结构·c++·算法·动态规划
副露のmagic15 小时前
数组章节 leetcode 思路&实现
算法·leetcode·职场和发展