-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0131.PalindromePartitioning.cpp
More file actions
56 lines (47 loc) · 1.14 KB
/
0131.PalindromePartitioning.cpp
File metadata and controls
56 lines (47 loc) · 1.14 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
51
52
53
54
55
56
class Solution {
public:
string* m_string;
int m_n;
vector<string> m_workingSet;
vector<vector<string>> m_sets;
const bool isPalindrome(int start, int end) {
// Check if not palindrome by counter-evidence.
while (start < end) {
// Check counter evidence.
if ((*m_string)[start] != (*m_string)[end]) return false;
// Move pointers.
start++;
end--;
}
// Is a palindrome.
return true;
}
void getPalindromeSets(const int index) {
if (index >= m_n) {
// Add partitions to total sets.
m_sets.push_back(m_workingSet);
return;
}
for (int i = index; i < m_n; i++) {
if (!isPalindrome(index, i)) continue;
// Add palindrome to working set.
m_workingSet.push_back(m_string->substr(index, (i - index) + 1));
// Work on next partition.
getPalindromeSets(i + 1);
// Reset state.
m_workingSet.pop_back();
}
}
vector<vector<string>> partition(string s) {
// Speed thingies.
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
// Initialize calculation variables.
m_string = &s;
m_n = m_string->size();
// Calculate sets.
getPalindromeSets(0);
return m_sets;
}
};