Advertisement
Fastrail08

Palindrome Partitioning

May 6th, 2025 (edited)
208
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.31 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. bool palindromeChecker(string s){
  5.     for(int i = 0, j = s.size() - 1; i <= j; i++, j--){
  6.         if(s[i] != s[j]){
  7.             return false;
  8.         }
  9.     }
  10.     return true;
  11. }
  12.  
  13. void palindromePartition(string s, int index, vector<string> &result){
  14.     // base case
  15.     if(index >= s.size()){
  16.         bool allPalindrome = true;
  17.         for(string str : result){
  18.             allPalindrome = allPalindrome && palindromeChecker(str);
  19.         }
  20.         if(allPalindrome){
  21.             for(int i = 0; i < result.size(); i++){
  22.                 cout << '[' << result[i] << ']';
  23.             }
  24.             cout << '\n';
  25.         }
  26.         return;
  27.     }
  28.     // separate partition
  29.     char ch = s[index];
  30.     string chToStr = "";
  31.     chToStr += ch;
  32.     result.push_back(chToStr);
  33.     palindromePartition(s, index + 1, result);
  34.     result.pop_back();
  35.    
  36.     // no separate partition, to maintain order in partition, push in last subset only
  37.     if(result.size() > 0){
  38.         result[result.size() - 1] += chToStr;
  39.         palindromePartition(s, index + 1, result);
  40.         result[result.size() - 1].pop_back();
  41.     }
  42. }
  43.  
  44. int main() {
  45.     // your code goes here
  46.     string s;
  47.     cin >> s;
  48.     vector<string> result;
  49.     palindromePartition(s, 0, result);
  50. }
  51.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement