【leetcode】PalindromePartitioning
1,751 views
0
Question:
Given a string
s
, partition
s
such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of
s
.
For example, given
s
=
"aab"
,
Return
[ ["aa","b"], ["a","a","b"] ]
Anwser 1 :
class Solution { public: vector<vector<string>> partition(string s) { // Start typing your C/C++ solution below // DO NOT write int main() function vector<vector<string>> ret; if(s.length() == 0) return ret; vector<int> vec; vec.push_back(-1); part(s, 0, ret, vec); return ret; } void part(string s, int i, vector<vector<string>> &ret, vector<int> &vec) { if(i == s.length()){ vector<string> v; int len = vec.size(); for(int k = 0; k < len-1; k++) v.push_back(s.substr(vec[k]+1, vec[k+1] - vec[k])); ret.push_back(v); return; } for(int j = i; j < s.length(); j++) { if(isPalindrome(s, i, j)) { vec.push_back(j); part(s, j+1, ret, vec); vec.pop_back(); } } } bool isPalindrome(string &s, int i, int j) { while(i < j) { if(s[i++] != s[j--]) return false; } return true; } };
Anwser 2 :
class Solution { public: vector<vector<string>> partition(string s) { // Start typing your C/C++ solution below // DO NOT write int main() function int len=s.length(); int BIG=2*len; int num_line=len+1; vector<int> vec(num_line*num_line); for(int l=1; l<=len; l++)//两个木板之间有多少个字符 { for (int i=0; i+l<num_line; i++)//从第0个木板开始,i+l为木板的序号 { if (l==1) { vec[i*num_line+(i+l)]=1; } else if(l==2) { if (s[i]==s[i+l-1]) vec[i*num_line+(i+l)]=1; else vec[i*num_line+(i+l)]=BIG; } else { if (s[i]==s[i+l-1]) vec[i*num_line+(i+l)] = vec[(i+1)*num_line+(i+l-1)]; else vec[i*num_line+(i+l)]=BIG; } } } vector<vector<int>> index; vector<int> start; start.push_back(0); index.push_back(start); for (int i=0;i<num_line;i++) { int max_len=index.size(); vector<vector<int>>::iterator iter=index.begin(); for(int j=0;j<max_len;j++) { vector<int> current_line=index[j]; if (current_line.back()>=num_line-1) continue; bool first_time=true; for(int a=current_line.back()+1;a<num_line;a++) { if(vec[current_line.back()*num_line+a]==1) { if (first_time) { index[j].push_back(a); first_time=false; } else { vector<int> tmp=current_line; tmp.push_back(a); index.insert(index.begin()+j,tmp); j++; max_len++; } } } } } vector<vector<string>> res; for(int i=0;i<index.size();i++) { vector<string> tmp; res.push_back(tmp); for(int j=0;j<index[i].size()-1;j++) { res[i].push_back(s.substr(index[i][j],index[i][j+1]-index[i][j])); } } return res; } };
参考推荐:
版权所有: 本文系米扑博客原创、转载、摘录,或修订后发表,最后更新于 2013-04-14 13:48:57
侵权处理: 本个人博客,不盈利,若侵犯了您的作品权,请联系博主删除,莫恶意,索钱财,感谢!