-
Notifications
You must be signed in to change notification settings - Fork 0
/
131. Palindrome Partitioning.cpp
93 lines (81 loc) · 2.13 KB
/
131. Palindrome Partitioning.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
// ***
//
// Given a string s, partition s such that every substring of the partition is a palindrome.
//
// Return all possible palindrome partitioning of s.
//
// Example:
//
// Input: "aab"
// Output:
// [
// ["aa","b"],
// ["a","a","b"]
// ]
//
// ***
class Solution {
public:
vector<vector<string>> partition(string s) {
vector<string> current;
vector<vector<string>> all;
backtrack(s, current, all);
return all;
}
private:
void backtrack(string s, vector<string>& current, vector<vector<string>>& all) {
if (s.empty()) {
all.push_back(current);
return;
}
for (int i = 1; i <= s.size(); ++i) {
if (isPalindrome(s.substr(0, i))) {
current.push_back(s.substr(0, i));
backtrack(s.substr(i), current, all);
current.pop_back();
}
}
}
bool isPalindrome(string s) {
int left = 0, right = s.size() - 1;
while (left < right) {
if (s[left++] != s[right--]) {
return false;
}
}
return true;
}
};
// Same idea using startIndex instead of s.substr()
class Solution {
public:
vector<vector<string>> partition(string s) {
vector<string> current;
vector<vector<string>> all;
int startIndex = 0;
backtrack(s, startIndex, current, all);
return all;
}
private:
void backtrack(string s, int startIndex, vector<string>& current, vector<vector<string>>& all) {
if (startIndex == s.size()) {
all.push_back(current);
return;
}
for (int i = startIndex; i < s.size(); ++i) {
if (isPalindrome(s, startIndex, i)) {
current.push_back(s.substr(startIndex, i - startIndex + 1));
backtrack(s, i + 1, current, all);
current.pop_back();
}
}
}
bool isPalindrome(string s, int left, int right) {
while (left < right) {
if (s[left++] != s[right--]) {
return false;
}
}
return true;
}
};