-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy path131_PalindromePartitioning.cpp
72 lines (65 loc) · 1.63 KB
/
131_PalindromePartitioning.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
#include <string>
#include <vector>
#include <queue>
#include <iterator>
#include <iostream>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<vector<string>> partition(string s) {
vector<char const *> par;
vector<vector<string>> result;
partition(s.c_str(), (int)s.size(), par, result);
return result;
}
void partition(char const *s, int len, vector<char const *> &par, vector<vector<string>> &result)
{
par.push_back(s);
if (len == 0)
{
vector<string> tmp;
for (int i = 0; i < (int)par.size() - 1; ++i)
tmp.emplace_back(par[i], par[i + 1]);
result.push_back(move(tmp));
}
else
{
for (int i = 1; i <= len; ++i)
{
if (isPalindrome(s, i))
{
partition(s + i, len - i, par, result);
}
}
}
par.pop_back();
}
bool isPalindrome(char const *s, int len)
{
int half = len / 2;
for (int i = 0; i < half; ++i)
{
if (s[i] != s[len - 1 - i])
return false;
}
return true;
}
};
int main()
{
for (auto test : vector<string>
{
"", "a", "aab", "aabbaba"
})
{
auto result = Solution().partition(test);
cout << "------------\n";
for (auto &par : result)
{
for (auto &s : par)
cout << s << ",";
cout << "\n";
}
}
}