Print all palindromic partitions of a string in C++

C++Server Side ProgrammingProgramming

<p style="">In this problem, we are given a palindromic string. And we have to print all the partitions of this string. In this problem, we will find all possible palindrome partitions of the string by cutting it.</p><p>Let&rsquo;s take an example to understand the problem -</p><p style=""><strong>Input</strong> &minus; string = &lsquo;ababa&rsquo;<br><strong>Output</strong> &minus; ababa , a bab a, a b a b a &hellip;.</p><p style="">The solution, to this problem, is to check if a substring is a palindrome or not. And print the substring if it is substring.</p><h2 style="">Example</h2><p style="">The below program will illustrate the solution &minus;</p><p><a class="demo" href="" rel="nofollow" target="_blank">&nbsp;Live Demo</a></p><pre class="prettyprint notranslate">#include&lt;bits/stdc++.h&gt; using namespace std; bool isPalindrome(string str, int low, int high){ &nbsp; &nbsp;while (low &lt; high) { &nbsp; &nbsp; &nbsp; if (str[low] != str[high]) &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return false; &nbsp; &nbsp; &nbsp; low++; &nbsp; &nbsp; &nbsp; high--; &nbsp; &nbsp;} &nbsp; &nbsp;return true; } void palindromePartition(vector&lt;vector&lt;string&gt; &gt;&amp;allPart, vector&lt;string&gt; &amp;currPart, int start, int n, string str){ &nbsp; &nbsp;if (start &gt;= n) { &nbsp; &nbsp; &nbsp; allPart.push_back(currPart); &nbsp; &nbsp; &nbsp; return; &nbsp; &nbsp;} &nbsp; &nbsp;for (int i=start; i&lt;n; i++){ &nbsp; &nbsp; &nbsp; if (isPalindrome(str, start, i)) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;currPart.push_back(str.substr(start, i-start+1)); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;palindromePartition(allPart, currPart, i+1, n, str); &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;currPart.pop_back(); &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp;} } void generatePalindromePartitions(string str){ &nbsp; &nbsp;int n = str.length(); &nbsp; &nbsp;vector&lt;vector&lt;string&gt; &gt; partitions; &nbsp; &nbsp;vector&lt;string&gt; currPart; &nbsp; &nbsp;palindromePartition(partitions, currPart, 0, n, str); &nbsp; &nbsp;for (int i=0; i&lt; partitions.size(); i++ ) { &nbsp; &nbsp; &nbsp; for (int j=0; j&lt;partitions[i].size(); j++) &nbsp; &nbsp; &nbsp; cout&lt;&lt;partitions[i][j]&lt;&lt;&quot; &quot;; &nbsp; &nbsp; &nbsp; cout&lt;&lt;endl; &nbsp; &nbsp;} } int main() { &nbsp; &nbsp;string str = &quot;abaaba&quot;; &nbsp; &nbsp;cout&lt;&lt;&quot;Palindromic partitions are : &quot;; &nbsp; &nbsp;generatePalindromePartitions(str); &nbsp; &nbsp;return 0; }</pre><h2>Output</h2><pre class="result notranslate">Palindromic partitions are : a b a a b a a b a aba a b aa b a a baab a aba a b a aba aba abaaba</pre>
Updated on 14-Jul-2020 07:35:42