-
Notifications
You must be signed in to change notification settings - Fork 0
/
131.cpp
110 lines (92 loc) · 2.19 KB
/
131.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
#include<bits/stdc++.h>
using namespace std;
class Solution3 {
vector<vector<string>> result;
vector<string> curr;
bool ispalin(string &s){
return s == string(s.rbegin(), s.rend());
}
void partition(int i, string &s){
if(i == s.size()){
if(ispalin(curr.back()))
result.push_back(curr);
return;
}
char c = s[i];
curr.back().push_back(c);
partition(i+1, s);
curr.back().pop_back();
if(ispalin(curr.back())){
curr.push_back(string{c});
partition(i+1, s);
curr.pop_back();
}
}
public:
vector<vector<string>> partition(string s) {
result = vector<vector<string>>{};
curr = vector<string>{string{s[0]}};
partition(1,s);
return result;
}
};
class Solution2 {
bool ispalin(string &s){
return s == string(s.rbegin(), s.rend());
}
public:
vector<vector<string>> partition(string s) {
vector<vector<string>> parts {{string{s[0]}}};
for(int i = 1; i < s.size(); i++){
vector<vector<string>> tmp;
char c = s[i];
for(auto part: parts){
if(ispalin(part.back())){
part.push_back(string{c});
tmp.push_back(part);
part.pop_back();
}
part.back().push_back(c);
tmp.push_back(part);
}
parts = tmp;
}
auto new_end = remove_if(parts.begin(), parts.end(),
[&](auto &part){
return !ispalin(part.back());
});
parts.erase(new_end, parts.end());
return parts;
}
};
// First find all possible ways to partition the string
// then remove all ways where any substr is not palin.
class Solution1 {
public:
vector<vector<string>> partition(string s) {
vector<vector<string>> parts {{string{s[0]}}};
for(int i = 1; i < s.size(); i++){
vector<vector<string>> tmp;
char c = s[i];
for(auto part: parts){
part.push_back(string{c});
tmp.push_back(part);
part.pop_back();
part.back().push_back(c);
tmp.push_back(part);
}
parts = tmp;
}
auto notPalin = [](string &ss){
return ss != string(ss.rbegin(), ss.rend());
};
auto predicate = [notPalin](auto part) {
return any_of(part.begin(), part.end(), notPalin);
};
auto new_end = remove_if(parts.begin(), parts.end(), predicate);
parts.erase(new_end, parts.end());
return parts;
}
};
int main(){
}