-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPalindrome Partitioning.h
More file actions
50 lines (43 loc) · 1.47 KB
/
Palindrome Partitioning.h
File metadata and controls
50 lines (43 loc) · 1.47 KB
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
class Solution {
public:
vector<vector<string>> partition(string s) {
vector<vector<string> > res;
if(s.empty()) return res;
vector<bool> v(s.size(), false);
vector<vector<bool> > isPal(s.size(), v);
preprocess(isPal, s); //O(n^2)
vector<string> empty;
generateParts(s, 0, empty, res, isPal); //O(n^2)
return res;
}
private:
void generateParts(const string &s, int pos, vector<string> & curr, vector<vector<string> > & res, const vector<vector<bool> > &isPal) {
if(pos == s.size()) {
vector<string> copy(curr);
res.push_back(curr);
return;
}
for(int i = pos; i < s.size(); ++i) {
if(isPal[pos][i]) {
curr.push_back(s.substr(pos, i - pos + 1));
generateParts(s, i+1, curr, res, isPal);
curr.pop_back();
}
}
}
void preprocess(vector<vector<bool> > &isPal, const string &s) {
for(int i = 0; i < s.size(); ++i) {
isPal[i][i] = true;
}
for(int len = 2; len <= isPal.size(); ++len) {
for(int i = 0; i < isPal.size() - len + 1; ++i) {
int a = i+len - 1;
if(len < 3) {
isPal[i][a] = (s[i] == s[a]);
} else {
isPal[i][a] = (s[i] == s[a]) && isPal[i+1][a-1];
}
}
}
}
};