代码改变世界

leetcode - Palindrome Partitioning

2013-12-14 09:23  张汉生  阅读(213)  评论(0编辑  收藏  举报

 

 

 1 class Solution {
 2 public:
 3     bool isPal(const char * p, const char * q){
 4         while (p<q){
 5             if (*p != *q)
 6                 return false;
 7             p++; q--;
 8         }
 9         return true;
10     }
11     vector<vector<string> > partition(string s) {
12         int n = s.length();
13         if (n<=0)
14             return vector<vector<string>>(1,vector<string>(1,""));
15         const char * head = s.c_str();
16         const char * end = head + n-1;
17         const char * p = head;
18         vector<vector<vector<const char *> > > ePos(n+1, vector<vector<const char*> >());
19         ePos[0].push_back(vector<const char*>());
20         while ((*p) != '\0'){
21             const char * q = head;
22             vector<vector<const char*> >& cur = ePos[p-head+1];
23             while (q<=p){
24                 if (! isPal(q,p)){
25                     q++;
26                     continue;
27                 }
28                 vector<vector<const char*> >& before = ePos[q-head];
29                 vector<vector<const char*> >::iterator vvci;
30                 for (vvci = before.begin(); vvci != before.end(); vvci++){
31                     vector<const char*> vc = *vvci;
32                     vc.push_back(p);
33                     cur.push_back(vc);
34                 }
35                 q++;
36             }
37             p++;
38         }
39         vector<vector<string>> rlt;
40         for (vector<vector<const char*> >::iterator vvci = ePos[n].begin(); vvci!=ePos[n].end();vvci++){
41             vector<string> sol;
42             const char * cItr = head;
43             for (vector<const char*>::iterator vci=(*vvci).begin(); vci!=(*vvci).end(); vci++){
44                 string tmp = "";
45                 while (true){
46                     tmp += *cItr;
47                     if (cItr == *vci)
48                         break;
49                     cItr++;
50                 }
51                 cItr++;
52                 sol.push_back(tmp);
53             }
54             rlt.push_back(sol);
55         }
56         return rlt;
57     }
58 };