Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 4c93517

Browse files
committed
"Palindrome Partitioning"
1 parent 6121422 commit 4c93517

File tree

2 files changed

+61
-1
lines changed

2 files changed

+61
-1
lines changed

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -169,7 +169,7 @@ The `☢` means that you need to have a LeetCode Premium Subscription.
169169
| 134 | [Gas Station] | [C](src/134.c) |
170170
| 133 | [Clone Graph] | [C++](src/133.cpp) |
171171
| 132 | [Palindrome Partitioning II] | |
172-
| 131 | [Palindrome Partitioning] | |
172+
| 131 | [Palindrome Partitioning] | [C++](src/131.cpp) |
173173
| 130 | [Surrounded Regions] | |
174174
| 129 | [Sum Root to Leaf Numbers] | [C](src/129.c) |
175175
| 128 | [Longest Consecutive Sequence] | [C](src/128.c) |

‎src/131.cpp‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
#include <iostream>
2+
#include <string>
3+
#include <vector>
4+
5+
using namespace std;
6+
7+
class Solution {
8+
public:
9+
vector<vector<string>> partition(string s) {
10+
vector<vector<string>> ans;
11+
vector<string> temp;
12+
partitionHelper(ans, temp, s);
13+
return ans;
14+
}
15+
16+
void partitionHelper(vector<vector<string>> &ans, vector<string> &temp, string s) {
17+
if (s.length() == 0) {
18+
ans.push_back(temp);
19+
return;
20+
}
21+
22+
if (s.length() == 1) {
23+
temp.push_back(s);
24+
ans.push_back(temp);
25+
temp.pop_back();
26+
return;
27+
}
28+
29+
for (int i = 0; i < s.length(); i++) {
30+
if(isPalindrome(s.substr(0, i + 1))) {
31+
temp.push_back(s.substr(0, i + 1));
32+
partitionHelper(ans, temp, s.substr(i + 1));
33+
temp.pop_back();
34+
}
35+
}
36+
}
37+
38+
bool isPalindrome(string s) {
39+
int i = 0, j = s.length() - 1;
40+
while (i < j) {
41+
if (s[i] != s[j]) return false;
42+
i++; j--;
43+
}
44+
return true;
45+
}
46+
};
47+
48+
int main() {
49+
Solution s;
50+
auto ans = s.partition("aaaba");
51+
52+
for (int i = 0; i < ans.size(); i++) {
53+
for (int j = 0; j < ans[i].size(); j++) {
54+
cout << ans[i][j] << " ";
55+
}
56+
cout << endl;
57+
}
58+
59+
return 0;
60+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /