-
Notifications
You must be signed in to change notification settings - Fork 119
/
131.cpp
60 lines (51 loc) · 1.32 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
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
vector<vector<string>> partition(string s) {
vector<vector<string>> ans;
vector<string> temp;
partitionHelper(ans, temp, s);
return ans;
}
void partitionHelper(vector<vector<string>> &ans, vector<string> &temp, string s) {
if (s.length() == 0) {
ans.push_back(temp);
return;
}
if (s.length() == 1) {
temp.push_back(s);
ans.push_back(temp);
temp.pop_back();
return;
}
for (int i = 0; i < s.length(); i++) {
if(isPalindrome(s.substr(0, i + 1))) {
temp.push_back(s.substr(0, i + 1));
partitionHelper(ans, temp, s.substr(i + 1));
temp.pop_back();
}
}
}
bool isPalindrome(string s) {
int i = 0, j = s.length() - 1;
while (i < j) {
if (s[i] != s[j]) return false;
i++; j--;
}
return true;
}
};
int main() {
Solution s;
auto ans = s.partition("aaaba");
for (int i = 0; i < ans.size(); i++) {
for (int j = 0; j < ans[i].size(); j++) {
cout << ans[i][j] << " ";
}
cout << endl;
}
return 0;
}