Print all Palindromic Partitions of a String using Backtracking
Last Updated :
09 Nov, 2023
Given a string, find all possible palindromic partitions of given string.
Note that this problem is different from Palindrome Partitioning Problem, there the task was to find the partitioning with minimum cuts in input string. Here we need to print all possible partitions.
Example:
Input: nitin
Output: n i t i n
n iti n
nitin
Input: geeks
Output: g e e k s
g ee k s
Brute Force Approach:
The idea is to use recursion and backtracking.
- Partition the string to generate the substrings.
- Check whether the substring generated is palindrome or not.
- If the substring generated is palindrome,
- then add this substring to our current list and recursively call the function for the remaining string.
- When the end of the string is reached the current list is added to the result.
Below is the implementation of above approach.
C++
#include <bits/stdc++.h>
using namespace std;
class GFG {
public :
bool checkPalindrome(string& s)
{
int n = s.size();
int i = 0, j = n - 1;
while (i < j) {
if (s[i] != s[j])
return false ;
i++;
j--;
}
return true ;
}
void Partition(vector<vector<string> >& res, string& s,
int idx, vector<string>& curr)
{
if (idx == s.size()) {
res.push_back(curr);
return ;
}
string t;
for ( int i = idx; i < s.size(); i++) {
t.push_back(s[i]);
if (checkPalindrome(t)) {
curr.push_back(t);
Partition(res, s, i + 1, curr);
curr.pop_back();
}
}
}
};
int main()
{
GFG ob;
vector<vector<string> > res;
string s = "geeks" ;
int idx = 0;
vector<string> curr;
ob.Partition(res, s, idx, curr);
for ( auto & v : res) {
for ( auto & it : v) {
cout << it << " " ;
}
cout << "\n" ;
}
return 0;
}
|
Java
import java.io.*;
import java.util.ArrayList;
class GFG {
public boolean checkPalindrome(String s) {
int n = s.length();
int i = 0 ;
int j = n- 1 ;
while (i < j) {
if (s.charAt(i) != s.charAt(j))
return false ;
i++;
j--;
}
return true ;
}
public void partition(ArrayList<ArrayList<String>> res, String s, int ind, ArrayList<String> curr) {
if (ind == s.length()) {
res.add( new ArrayList<String>(curr));
return ;
}
String temp = "" ;
for ( int i = ind; i < s.length(); i++) {
temp += s.charAt(i);
if (checkPalindrome(temp)){
curr.add(temp);
partition(res, s, i+ 1 , curr);
curr.remove(curr.size()- 1 );
}
}
}
public static void main(String[] args) {
GFG obj = new GFG();
ArrayList<ArrayList<String>> res = new ArrayList<>();
String s = "geeks" ;
int ind = 0 ;
ArrayList<String> curr = new ArrayList<>();
obj.partition(res, s, ind, curr);
for (ArrayList<String> iter : res) {
System.out.println(iter);
}
}
}
|
Python
class GFG:
def checkPalindrome( self , s):
n = len (s)
i, j = 0 , n - 1
while i < j:
if s[i] ! = s[j]:
return False
i + = 1
j - = 1
return True
def partition( self , res, s, ind, curr):
if ind = = len (s):
res.append( list (curr))
return
temp = ""
for i in range (ind, len (s)):
temp + = s[i]
if self .checkPalindrome(temp):
curr.append(temp)
self .partition(res, s, i + 1 , curr)
curr.pop()
def main( self ):
obj = GFG()
res = []
s = "geeks"
ind = 0
curr = []
obj.partition(res, s, ind, curr)
for iter in res:
print ( iter )
gfg_obj = GFG()
gfg_obj.main()
|
C#
using System;
using System.Collections.Generic;
class GFG {
public bool CheckPalindrome( string s)
{
int n = s.Length;
int i = 0, j = n - 1;
while (i < j) {
if (s[i] != s[j])
return false ;
i++;
j--;
}
return true ;
}
public void Partition(List<List< string > > res, string s,
int idx, List< string > curr)
{
if (idx == s.Length) {
res.Add( new List< string >(curr));
return ;
}
string t = "" ;
for ( int i = idx; i < s.Length; i++) {
t += s[i];
if (CheckPalindrome(t)) {
curr.Add(t);
Partition(res, s, i + 1, curr);
curr.RemoveAt(curr.Count - 1);
}
}
}
public static void Main( string [] args)
{
GFG ob = new GFG();
List<List< string > > res = new List<List< string > >();
string s = "geeks" ;
int idx = 0;
List< string > curr = new List< string >();
ob.Partition(res, s, idx, curr);
foreach ( var v in res)
{
foreach ( var it in v)
{
Console.Write(it + " " );
}
Console.WriteLine();
}
}
}
|
Javascript
class GFG {
checkPalindrome(s) {
let n = s.length;
let i = 0, j = n - 1;
while (i < j) {
if (s[i] !== s[j]) {
return false ;
}
i++;
j--;
}
return true ;
}
partition(res, s, idx, curr) {
if (idx === s.length) {
res.push([...curr]);
return ;
}
let t = '' ;
for (let i = idx; i < s.length; i++) {
t += s[i];
if ( this .checkPalindrome(t)) {
curr.push(t);
this .partition(res, s, i + 1, curr);
curr.pop();
}
}
}
}
function main() {
const ob = new GFG();
const res = [];
const s = "geeks" ;
let idx = 0;
const curr = [];
ob.partition(res, s, idx, curr);
for (let v of res) {
console.log(v.join( ' ' ));
}
}
main();
|
Output
g e e k s
g ee k s
Time complexity: O(n*2n), where n is the size of the string. There are 2n possibilities of partitioning the string of length n, and for each possibility, we are checking if the string is a palindrome that costs O(n) time. Hence the overall time complexity is O(n*2n).
Auxiliary Space: O(2n), to store all possible partition of string.
Also read about the Bit Manipulation approach or this problem.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...