【代码随想录day 22】 力扣 131.分割回文串
视频讲解;https://www.bilibili.com/video/BV1c54y1e7k6/?vd_source=a935eaede74a204ec74fd041b917810c
文档讲解:https://programmercarl.com/0131.%E5%88%86%E5%89%B2%E5%9B%9E%E6%96%87%E4%B8%B2.html#%E6%80%9D%E8%B7%AF
力扣题目:https://leetcode.cn/problems/palindrome-partitioning/
这道题主要思路如下:
- 遍历字符串,将遍历的stattIndex抽象成切割的位置,如果从startIndex到当前位置是回文子串,用substr切割,如果不是直接跳过。
- 当startIndex遍历到字符串末尾时代表结束,path存入result数组中。
- 在遍历过程中,只有回文子串才会一直执行代码,如果不是,直接跳过不会执行代码,更不会往result中存入path。
- 在判断回文子串的过程中,如果暂时不是回文子串不能直接ruturn,要继续切割,比如efe,如果切割ef和e他不是回文子串,但是efe是回文子串,所以如果不是回文子串,要用continue继续执行代码。
class Solution {
private:vector<string> path;vector<vector<string>> result;void backtracking( const string &s, int startindex){//判断终止条件if(startindex == s.size()){result.push_back(path);return;}//单层遍历for(int i = startindex; i<s.size();i++){//判断切割点之前是否是回文子串if(isPalindrome(s, startindex, i)){//substr函数截取字符串string str = s.substr(startindex, i - startindex + 1);path.push_back(str);}else continue;//遍历backtracking(s, i+1);path.pop_back();}}bool isPalindrome(const 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;}
public:vector<vector<string>> partition(string s) {result.clear();path.clear();backtracking(s, 0);return result;}
};