-
Notifications
You must be signed in to change notification settings - Fork 0
/
PALIDROME.cpp
83 lines (72 loc) · 2.01 KB
/
PALIDROME.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
// C++ program to print all palindromic partitions of a given string
#include<bits/stdc++.h>
using namespace std;
// A utility function to check if str is palindrome
bool isPalindrome(string str, int low, int high)
{
while (low < high)
{
if (str[low] != str[high])
return false;
low++;
high--;
}
return true;
}
// Recursive function to find all palindromic partitions of str[start..n-1]
// allPart --> A vector of vector of strings. Every vector inside it stores
// a partition
// currPart --> A vector of strings to store current partition
void allPalPartUtil(vector<vector<string> >&allPart, vector<string> &currPart,
int start, int n, string str)
{
// If 'start' has reached len
if (start >= n)
{
allPart.push_back(currPart);
return;
}
// Pick all possible ending points for substrings
for (int i=start; i<n; i++)
{
// If substring str[start..i] is palindrome
if (isPalindrome(str, start, i))
{
// Add the substring to result
currPart.push_back(str.substr(start, i-start+1));
// Recur for remaining remaining substring
allPalPartUtil(allPart, currPart, i+1, n, str);
// Remove substring str[start..i] from current
// partition
currPart.pop_back();
}
}
}
// Function to print all possible palindromic partitions of
// str. It mainly creates vectors and calls allPalPartUtil()
void allPalPartitions(string str)
{
int n = str.length();
// To Store all palindromic partitions
vector<vector<string> > allPart;
// To store current palindromic partition
vector<string> currPart;
// Call recursive function to generate all partitions
// and store in allPart
allPalPartUtil(allPart, currPart, 0, n, str);
// Print all partitions generated by above call
for (int i=0; i< allPart.size(); i++ )
{
for (int j=0; j<allPart[i].size(); j++)
cout << allPart[i][j] << " ";
cout << "\n";
cout << "\n";
}
}
// Driver program
int main()
{
string str = "nitin";
allPalPartitions(str);
return 0;
}