forked from sourav-122/hacktoberfest2022
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Palindrome_Partitioning.cpp
62 lines (57 loc) · 1.63 KB
/
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
/*Palindrome Partitioning
Problem Statement: You are given a string s, partition it in such a way that every substring is a palindrome. Return all such palindromic partitions of s.
Note: A palindrome string is a string that reads the same backward as forward.
Input: s = “aabb”
Output: [ [“a”,”a”,”b”,”b”], [“aa”,”bb”], [“a”,”a”,”bb”], [“aa”,”b”,”b”] ]
*/
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector < vector < string >> partition(string s) {
vector < vector < string > > res;
vector < string > path;
partitionHelper(0, s, path, res);
return res;
}
void partitionHelper(int index, string s, vector < string > & path,
vector < vector < string > > & res) {
if (index == s.size()) {
res.push_back(path);
return;
}
for (int i = index; i < s.size(); ++i) {
if (isPalindrome(s, index, i)) {
path.push_back(s.substr(index, i - index + 1));
partitionHelper(i + 1, s, path, res);
path.pop_back();
}
}
}
bool isPalindrome(string s, int start, int end) {
while (start <= end) {
if (s[start++] != s[end--])
return false;
}
return true;
}
};
int main() {
string s = "aabb";
Solution obj;
vector < vector < string >> ans = obj.partition(s);
int n = ans.size();
cout << "The Palindromic partitions are :-" << endl;
cout << " [ ";
for (auto i: ans) {
cout << "[ ";
for (auto j: i) {
cout << j << " ";
}
cout << "] ";
}
cout << "]";
return 0;
}
//Time Complexity: O( (2^n) *k*(n/2) )
//Space Complexity: O(k * x)