2021.3.17刷题-分割回文串

题目链接:https://leetcode-cn.com/problems/palindrome-partitioning
题目描述:
给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是 回文串 。返回 s 所有可能的分割方案。
回文串 是正着读和反着读都一样的字符串。

示例 1:
输入:s = "aab"
输出:[["a","a","b"],["aa","b"]]

示例 2:
输入:s = "a"
输出:[["a"]]

解题:

class Solution {
public:
    vector<vector<string>> ans;
    vector<string> path;
    void trackingback(string &s, int startIndex){
        if(startIndex >= s.size())
        {
            ans.push_back(path);
        }
        for(int i = startIndex; i < s.size(); i++)
        {
            if(isPalindromic(s, startIndex, i))  
            {
                string str = s.substr(startIndex, i - startIndex + 1);  //切割字符串
                path.push_back(str);
            }else{
                continue;  //如果不是回文字符串,直接跳过
            }
            trackingback(s, i + 1);
            path.pop_back();
               
        }
    }

    //判断字符串是否是回文字符串
    bool isPalindromic(string s, int start, int end)
    {
        int i, j;
        for(i = start, j = end; i < j; i++, j--)
        {
            if(s[i] != s[j])
                return false;
        }
        return true;
    }

    vector<vector<string>> partition(string s) {
        trackingback(s, 0);
        return ans;
    }
};
原文地址:https://www.cnblogs.com/ZigHello/p/14549622.html