leetcode:Palindrome Partitioning

来源:互联网 发布:数据结构必背算法 编辑:程序博客网 时间:2024/05/17 02:01

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"]  ]

vector<vector<string>> partition(string s){/*在s的len个字符之间放len-1个木板,并且在两端个放一个,这样就有len+1个木板*/int len=s.length();int BIG=2*len;int num_line=len+1;//表明两个木板之间substr是否为回文,如果有则代表它两端的木板可以直接相连,//否则,代表它两端的木板必须通过其他木板相连,也就是不相连//将这些木板作为节点,上面的连接关系作为边,建立图vector<int> isPalindrome(num_line*num_line);/*if s[i]==s[j]f(i,j)=f(i+1,j-1)elsef(i,j)=0*/for(int l=1;l<=len;l++)//两个木板之间有多少个字符{for (int i=0;i+l<num_line;i++)//从第0个木板开始,i+l为木板的序号{if (l==1){isPalindrome[i*num_line+(i+l)]=1;}else if(l==2){if (s[i]==s[i+l-1])isPalindrome[i*num_line+(i+l)]=1;elseisPalindrome[i*num_line+(i+l)]=BIG;}else{if (s[i]==s[i+l-1])isPalindrome[i*num_line+(i+l)]=isPalindrome[(i+1)*num_line+(i+l-1)];elseisPalindrome[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(isPalindrome[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;}

原创粉丝点击