-
Notifications
You must be signed in to change notification settings - Fork 110
Expand file tree
/
Copy path132-palindrome-partitioning.cpp
More file actions
38 lines (35 loc) · 991 Bytes
/
132-palindrome-partitioning.cpp
File metadata and controls
38 lines (35 loc) · 991 Bytes
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
class Solution {
public:
bool isPalindrome(string str) {
int n = str.size();
int i = 0, j = n - 1;
while (i < j) {
if (str[i] != str[j]) {
return false;
} else {
i++;
j--;
}
}
return true;
}
int minCut(string s) {
int n = s.size();
if (n <= 1) return 0;
vector<int> minCuts(n, INT_MAX);
minCuts[0] = 0;
for (int i = 0; i < n; i++) {
if (isPalindrome(s.substr(0, i + 1))) {
minCuts[i] = 0;
} else {
minCuts[i] = minCuts[i - 1] + 1;
for (int j = 1; j < i; j++) {
if (isPalindrome(s.substr(j, i - j + 1)) && minCuts[i] > minCuts[j - 1] + 1) {
minCuts[i] = minCuts[j - 1] + 1;
}
}
}
}
return minCuts[n - 1];
}
};