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 642fbb4

Browse files
committed
"Palindrome Partitioning II"
1 parent 4c93517 commit 642fbb4

File tree

2 files changed

+71
-1
lines changed

2 files changed

+71
-1
lines changed

‎README.md

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

‎src/132.cpp

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
#include <iostream>
2+
#include <string>
3+
#include <vector>
4+
#include <cassert>
5+
6+
using namespace std;
7+
8+
class Solution {
9+
public:
10+
int minCut(string s) {
11+
int n = s.length();
12+
if (n == 0) return 0;
13+
14+
vector<int> dp(n);
15+
vector<vector<int> > mem(n, vector<int>(n)); // memorization for palindrome
16+
17+
int i, j, k;
18+
// build palindrome table
19+
for (i = 0; i < n; i++) {
20+
mem[i][i] = 1;
21+
j = i, k = i + 1; // even length
22+
while(j >= 0 && k <= n - 1) {
23+
if (s[j] != s[k]) break;
24+
mem[j][k] = 1;
25+
j--;
26+
k++;
27+
}
28+
j = i - 1, k = i + 1; // odd length
29+
while(j >= 0 && k <= n - 1) {
30+
if (s[j] != s[k]) break;
31+
mem[j][k] = 1;
32+
j--;
33+
k++;
34+
}
35+
}
36+
37+
// run dynamic programming
38+
dp[0] = 0;
39+
for (i = 1; i < n; i++) {
40+
if (mem[0][i]) {
41+
dp[i] = 0;
42+
}
43+
else {
44+
int min = dp[i - 1] + 1;
45+
for (j = 0; j < i; j++) {
46+
if (mem[j + 1][i] && dp[j] + 1 < min) {// if right half is palindrome
47+
min = dp[j] + 1;
48+
}
49+
}
50+
dp[i] = min;
51+
}
52+
}
53+
54+
return dp[n - 1];
55+
}
56+
};
57+
58+
int main() {
59+
string str0 = "aababa";
60+
string str1 = "ababa";
61+
62+
Solution s;
63+
64+
assert(s.minCut(str0) == 1);
65+
assert(s.minCut(str1) == 0);
66+
67+
printf("all tests passed!\n");
68+
69+
return 0;
70+
}

0 commit comments

Comments
(0)

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