-
Notifications
You must be signed in to change notification settings - Fork 3
/
palindrom.cpp
129 lines (111 loc) · 2.25 KB
/
palindrom.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class Solution {
public:
bool **palindrome;
int N;
/**
* @param s: A string
* @return: A list of lists of string
*/
bool isPalindrome(string &s, int start, int end)
{
return palindrome[start][end];
}
bool ** getIsPalindrome(string &s)
{
int n = s.length();
palindrome = new bool * [n]();
N = n;
for(int i = 0; i < n; i++)
{
palindrome[i] = new int [n]();
}
for(int i = 0; i < n; i++)
{
palindrome[i][i] = true;
}
for(int i = 0; i < n-1; i++)
{
palindrome[i][i+1] = (s.at(i) == s.at(i+1));
}
for(int start = 0; start < n; start++)
{
for(int length = 2;
length < n && (start+length) < n;
length++)
{
palindrome[start][start+length] = palindrome[start+1][start+length-1] &&
(s.at(start) == s.at(start+length));
}
}
return palindrome;
}
void destoryPalindrome(void)
{
for(int i = 0; i < N; i++)
{
delete palindrome[i];
}
delete [] palindrome;
}
vector<vector<string>> partition(string s) {
// write your code here
vector<vector<string>> vv;
getIsPalindrome(s);
for(int len = 1; len <= s.length(); len++)
{
vector<string> v = cutPalindrome(s, len, 0, s.length()-1);
if(v.size() > 0)
{
vv.push_back(v);
}
}
destoryPalindrome();
return vv;
}
vector<string> cutPalindrome(string &s, int firstCutLen, int start, int end)
{
vector<string> v;
if(start > end)
{
return v;
}
if((firstCutLen == 0) ||
(firstCutLen > (end - start + 1)))
{
return v;
}
if(start == end)
{
v.push_back(s.substr(start, 1));
return v;
}
if(isPalindrome(s, start, start + firstCutLen-1))
{
v.push_back(s.substr(start, firstCutLen));
vector<string> remaining = cutPalindrome(s, start + firstCutLen, end);
v.insert(v.end(), remaining.begin(), remaining.end());
}
return v;
}
};
int main(void)
{
Solution mysol;
vector<vector<string> > myvv;
string str = "aabcb";
myvv = mysol.partition(str);
for(int i = 0; i < myvv.size(); i++)
{
vector<string> v = myvv[i];
for(int j=0; j < v.size(); j++)
{
cout <<v[j] <<" ";
}
cout << endl;
}
return 0;
}