-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
palindromePartitioning.cpp
121 lines (103 loc) · 3.11 KB
/
palindromePartitioning.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
// Source : https://oj.leetcode.com/problems/palindrome-partitioning/
// Author : Hao Chen
// Date : 2014-08-21
/**********************************************************************************
*
* Given a string s, partition s such that every substring of the partition is a palindrome.
*
* Return all possible palindrome partitioning of s.
*
* For example, given s = "aab",
*
* Return
*
* [
* ["aa","b"],
* ["a","a","b"]
* ]
*
*
**********************************************************************************/
#include <iostream>
#include <vector>
#include <string>
using namespace std;
bool isPalindrome(string &s, int start, int end) {
while(start < end)
{
if(s[start] != s[end]) {
return false;
}
start++; end--;
}
return true;
}
// DFS - Deepth First Search
//
// For example: "aaba"
//
// +------+
// +------| aaba |-----+
// | +------+ |
// +-v-+ +-v--+
// | a |aba | aa |ba
// +---+---+--+ +--+-+
// | | |
// +-v-+ +--v--+ +-v-+
// | a |ba | aba |\0 | b |a
// +-+-+ +-----+ +-+-+
// | a, aba |
// +-v-+ +-v-+
// | b |a | a |\0
// +-+-+ +---+
// | aa, b, a
// +-v-+
// | a |\0
// +---+
// a, a, b, a
//
// You can see this algorithm still can be optimized, becasue there are some dupliation.
// ( The optimization you can see the "Palindrome Partitioning II" )
//
void partitionHelper(string &s, int start, vector<string> &output, vector< vector<string> > &result) {
if (start == s.size()) {
result.push_back(output);
return;
}
for(int i=start; i<s.size(); i++) {
if ( isPalindrome(s, start, i) == true ) {
//put the current palindrome substring into ouput
output.push_back(s.substr(start, i-start+1) );
//Recursively check the rest substring
partitionHelper(s, i+1, output, result);
//take out the current palindrome substring, in order to check longer substring.
output.pop_back();
}
}
}
vector< vector<string> > partition(string s) {
vector< vector<string> > result;
vector<string> output;
partitionHelper(s, 0, output, result);
return result;
}
void printMatrix(vector< vector<string> > &matrix)
{
for(int i=0; i<matrix.size(); i++){
cout << "{ ";
for(int j=0; j< matrix[i].size(); j++) {
cout << matrix[i][j] << ", ";
}
cout << "}" << endl;
}
cout << endl;
}
int main(int argc, char** argv)
{
string s("aab");
if ( argc > 1 ){
s = argv[1];
}
vector< vector<string> > result = partition(s);
printMatrix(result);
}