本题与以前的回溯问题不同的地方在于操作对象是字符串而不是数组,并且本题要创建一个判断回文串的函数。
str.substr(index1,index2):用于截取字符串变量的一部分,第一个参数表示开始截取的位置,第二个参数表示截取的长度。
bool型:一般只占用一个字符的长度,真返回true(1),假返回false(0)
boolean型:是unsigned char类型
思路:使用回溯法,进入递归函数,如果起始位置已经等于字符串(s)的长度了,就保存该子串,并返回上一层递归函数;循环从startIndex开始,如果当前子串(下标从startIndex至 i 范围的s的子串)是回文串,就将结果压入中转栈(path),如果不是回文串,就用continue跳过后续递归,i 继续往后挪。
回文串采用了双指针法,一头一尾同时遍历字符串,头尾字符相同,就继续往中间遍历,直到头指针>尾指针(偶数)或 头指针=尾指针(奇数)。
我的代码:
class Solution {
public:
vector<vector<string>> partition(string s) {
backTracking(s,0);
return result;
}
vector<string> path;
vector<vector<string>> result;
void backTracking(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)){
path.push_back(s.substr(startIndex,i-startIndex+1));
//第一个参数是起始位置,第二个参数是截取的子串的长度
}else continue;
backTracking(s,i+1);
path.pop_back();
}
}
bool isPalindrome(string s,int startIndex,int i){
int left=startIndex;
int right=i;//双指针法
while(left<right){
if(s[left]==s[right]){
left++;
right--;
}else return false;
}
return true;
}
};
官方代码:
class Solution {
private:
vector<vector<string>> result;
vector<string> path; // 放已经回文的子串
void backtracking (const string& s, int startIndex) {
// 如果起始位置已经大于s的大小,说明已经找到了一组分割方案了
if (startIndex >= s.size()) {
result.push_back(path);
return;
}
for (int i = startIndex; i < s.size(); i++) {
if (isPalindrome(s, startIndex, i)) { // 是回文子串
// 获取[startIndex,i]在s中的子串
string str = s.substr(startIndex, i - startIndex + 1);
path.push_back(str);
} else { // 不是回文,跳过
continue;
}
backtracking(s, i + 1); // 寻找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;
}
};