131. 分割回文串
1 class Solution 2 { 3 public: 4 vector<vector<string>>result; 5 vector<string>temp; 6 7 bool isPalindrome(string s) //是否为回文串 8 { 9 int i=0,j=s.size()-1; 10 while(i<j) 11 { 12 if(s[i]!=s[j]) 13 return false; 14 i++; 15 j--; 16 } 17 return true; 18 } 19 20 void recursion(string s, int a, int b) //a <= b 21 { 22 //到字符串末尾了,将本次结果记录下来 23 if(a > b) 24 { 25 result.push_back(temp); 26 return; 27 } 28 //从index为a开始截取长度为1,2,3...的子串进行验证,成功则用剩下的部分递归。 29 for(int i = 1; i<=b-a+1;i++) 30 { 31 if(isPalindrome(s.substr(a,i))) 32 { 33 temp.push_back(s.substr(a,i)); 34 recursion(s,a+i,b); 35 temp.pop_back(); 36 } 37 } 38 } 39 40 vector<vector<string>> partition(string s) 41 { 42 recursion(s,0,s.size()-1); 43 return result; 44 } 45 };
Mamba never out

浙公网安备 33010602011771号