ARTICLE DETAIL

资讯详情

深耕网站建设、视觉设计与SEO优化的一线实战洞察。

131. 分割回文串

131. 分割回文串

题目描述

给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是 回文串 。返回 s 所有可能的分割方案。

回文串 是正着读和反着读都一样的字符串。

示例 1:

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

示例 2:

输入:s = "a"
输出:[["a"]]

提示:

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

解答

class Solution {
public:vector<vector<string>> res;vector<string> path;vector<vector<string>> partition(string s) {res.clear();path.clear();backtrack(s, 0);return res;}void backtrack(string &s, int startidx){// 分割起点大于等于字符串长度就说明本次分割完成,得到一组结果if(startidx >= s.size()){res.push_back(path);return;}// i 从 startidx 出发判断 [startidx, i]构成的字符串是否回文// 若是则加入临时结果中,进行后续的分割for(int i = startidx; i < s.size(); i++){if(isPalindrome(s, startidx, i)){string str = s.substr(startidx, i - startidx + 1);path.push_back(str);}   else{continue;}backtrack(s, i + 1);path.pop_back();}}bool isPalindrome(string &str, int start, int end){for(int i = start, j = end; i < j; i++, j--){if(str[i] != str[j]) return false;}return true;}
};
返回列表