Print all palindromic partitions of a string - GeeksforGeeks

24 Mar, 2020
Given a string s, partition s such that every string of the partition is a palindrome. Return all possible palindrome partitioning of s.
Example :
Input  : s = "bcc"
Output : [["b", "c", "c"], ["b", "cc"]]

Input  : s = "geeks"
Output : [["g", "e", "e", "k", "s"], 
          ["g", "ee", "k", "s"]]

We have to list the all possible partitions so we will think in the direction of recursion. When we are on index i, we incrementally check all substrings starting from i for being palindromic. If found, we recursively solve the problem for the remaining string and add this in our solution.
Following is the solution-
We will maintain a 2-dimensional vector for storing all possible partitions and a temporary vector for storing the current partition, new starting index of string to check partitions as we have already checked partitions before this index.Now keep on iterating further on string and check if it is palindrome or not.If it is a palindrome than add this string in current partitions vector. Recurse on this new string if it is not the end of the string. After coming back again change the current partition vector to the old one as it might have changed in the recursive step.If we reach the end of string while iterating than we have our partitions in our temporary vector so we will add it in results.
We will maintain a 2-dimensional vector for storing all possible partitions and a temporary vector for storing the current partition, new starting index of string to check partitions as we have already checked partitions before this index.
Now keep on iterating further on string and check if it is palindrome or not.
If it is a palindrome than add this string in current partitions vector. Recurse on this new string if it is not the end of the string. After coming back again change the current partition vector to the old one as it might have changed in the recursive step.
If we reach the end of string while iterating than we have our partitions in our temporary vector so we will add it in results.
To check whether it’s a palindrome or not, iterate on string by taking two pointers. Initialize the first to start and other to end of string. If both characters are same increase the first and decrease the last pointer and keep on iterating until first is less than last one.
C++
Java
Python3
C#
// C++ program to print all palindromic partitions// of a given string.#include <bits/stdc++.h>using namespace std;  // Returns true if str is palindrome, else falsebool checkPalindrome(string str){    int len = str.length();    len--;    for (int i=0; i<len; i++)    {        if (str[i] != str[len])            return false;        len--;    }    return true;}  void printSolution(vector<vector<string> > partitions){    for (int i = 0; i < partitions.size(); ++i)    {        for(int j = 0; j < partitions[i].size(); ++j)            cout << partitions[i][j] << " ";        cout << endl;    }    return;}  // Goes through all indexes and recursively add remaining// partitions if current string is palindrome.void addStrings(vector<vector<string> > &v, string &s,                vector<string> &temp, int index){    int len = s.length();    string str;    vector<string> current = temp;    if (index == 0)        temp.clear();    for (int i = index; i < len; ++i)    {        str = str + s[i];        if (checkPalindrome(str))        {            temp.push_back(str);            if (i+1 < len)                addStrings(v,s,temp,i+1);            else                v.push_back(temp);            temp = current;        }    }    return;}  // Generates all palindromic partitions of 's' and// stores the result in 'v'.void partition(string s, vector<vector<string> >&v){    vector<string> temp;    addStrings(v, s, temp, 0);    printSolution(v);    return;}  // Driver codeint main(){    string s = "geeks";    vector<vector<string> > partitions;    partition(s, partitions);    return 0;}
// Java program to print all palindromic partitions// of a given string.import java.util.ArrayList;public class GFG {         // Returns true if str is palindrome, else false    static boolean checkPalindrome(String str)    {        int len = str.length();        len--;        for (int i=0; i<len; i++)        {            if (str.charAt(i) != str.charAt(len))                return false;            len--;        }        return true;    }          // Prints the partition list    static void printSolution(ArrayList<ArrayList<String>>                                           partitions)    {        for(ArrayList<String> i: partitions)        {            for(String j: i)            {                System.out.print(j+" ");            }            System.out.println();        }    }           // Goes through all indexes and recursively add remaining    // partitions if current string is palindrome.    static ArrayList<ArrayList<String>> addStrings(ArrayList<       ArrayList<String>> v, String s, ArrayList<String> temp,                                              int index)    {        int len = s.length();        String str = "";        ArrayList<String> current = new ArrayList<>(temp);                  if (index == 0)            temp.clear();                  // Iterate over the string        for (int i = index; i < len; ++i)        {            str = str + s.charAt(i);                          // check whether the substring is             // palindromic or not            if (checkPalindrome(str))            {                // if palindrome add it to temp list                temp.add(str);                                  if (i + 1 < len)                {                        // recurr to get all the palindromic                    // partitions for the substrings                    v = addStrings(v,s,temp,i+1);                }                else                {                    // if end of the string is reached                     // add temp to v                    v.add(temp);                }                                  // temp is reinitialize with the                 // current i.                temp = new ArrayList<>(current);            }        }        return v;    }           // Generates all palindromic partitions of 's' and    // stores the result in 'v'.    static void partition(String s, ArrayList<ArrayList<                                          String>> v)    {        // temporary ArrayList to store each        // palindromic string        ArrayList<String> temp = new ArrayList<>();                  // calling addString method it adds all          // the palindromic partitions to v        v = addStrings(v, s, temp, 0);                  // printing the solution        printSolution(v);    }           // Driver code    public static void main(String args[])    {        String s = "geeks";        ArrayList<ArrayList<String>> partitions = new                                           ArrayList<>();        partition(s, partitions);    }}// This code is contributed by Sumit Ghosh
# Python3 program to print all palindromic # partitions of a given string.def checkPalindrome(string):          # Returns true if str is palindrome,     # else false    length = len(string)    length -= 1    for i in range(length):        if string[i] != string[length]:            return False        length -= 1    return True  def printSolution(partitions):    for i in range(len(partitions)):        for j in range(len(partitions[i])):            print(partitions[i][j], end = " ")        print()  def addStrings(v, s, temp, index):          # Goes through all indexes and     # recursively add remaining partitions     # if current string is palindrome.    length = len(s)    string = ""      current = temp[:]      if index == 0:        temp = []    for i in range(index, length):        string += s[i]        if checkPalindrome(string):            temp.append(string)            if i + 1 < length:                addStrings(v, s, temp[:], i + 1)            else:                v.append(temp)            temp = current  def partition(s, v):          # Generates all palindromic partitions     # of 's' and stores the result in 'v'.    temp = []    addStrings(v, s, temp[:], 0)    printSolution(v)  # Driver Codeif __name__ == "__main__":    s = "geeks"    partitions = []    partition(s, partitions)  # This code is contributed by# vibhu4agarwal
// C# program to print all palindromic partitions// of a given string.using System;using System.Collections.Generic;  class GFG {         // Returns true if str is palindrome, else false    static bool checkPalindrome(String str)    {        int len = str.Length;        len--;        for (int i = 0; i < len; i++)        {            if (str[i] != str[len])                return false;            len--;        }        return true;    }          // Prints the partition list    static void printSolution(List<List<String>>                                         partitions)    {        foreach(List<String> i in partitions)        {            foreach(String j in i)            {                Console.Write(j+" ");            }            Console.WriteLine();        }    }          // Goes through all indexes and recursively add remaining    // partitions if current string is palindrome.    static List<List<String>> addStrings(List<    List<String>> v, String s, List<String> temp,                                             int index)    {        int len = s.Length;        String str = "";        List<String> current = new List<String>(temp);                  if (index == 0)            temp.Clear();                  // Iterate over the string        for (int i = index; i < len; ++i)        {            str = str + s[i];                          // check whether the substring is             // palindromic or not            if (checkPalindrome(str))            {                // if palindrome add it to temp list                temp.Add(str);                                  if (i + 1 < len)                {                     // recurr to get all the palindromic                    // partitions for the substrings                    v = addStrings(v,s,temp,i+1);                }                else                {                    // if end of the string is reached                     // add temp to v                    v.Add(temp);                }                                  // temp is reinitialize with the                 // current i.                temp = new List<String>(current);            }        }        return v;    }          // Generates all palindromic partitions of 's' and    // stores the result in 'v'.    static void partition(String s, List<List<                                        String>> v)    {        // temporary List to store each        // palindromic string        List<String> temp = new List<String>();                  // calling addString method it adds all         // the palindromic partitions to v        v = addStrings(v, s, temp, 0);                  // printing the solution        printSolution(v);    }          // Driver code    public static void Main(String []args)    {        String s = "geeks";        List<List<String>> partitions = new                                        List<List<String>>();        partition(s, partitions);    }}  // This code is contributed by PrinciRaj1992
g e e k s 
g ee k s
Related Article:Dynamic Programming | Set 17 (Palindrome Partitioning)
This article is contributed by Anshul Goyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
vibhu4agarwal
princiraj1992
palindrome
Backtracking
Strings
Strings
Backtracking
palindrome
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Backtracking and Branch-N-Bound technique
Minimum Cost Path in a directed graph via given set of intermediate nodes
Tug of War
N-Queen Problem | Local Search using Hill climbing with random neighbour
Find if there is a path of more than k length from a source
Write a program to reverse an array or string
Reverse a string in Java
C++ Data Types
Longest Common Subsequence | DP-4
Check for Balanced Brackets in an expression (well-formedness) using Stack