RainX_69

PRINT DISTINCT PALINDROMIC PERMUTATIONS OF A STRING

Dec 30th, 2022
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.71 KB | Source Code | 0 0
  1. /*
  2. link- https://www.lintcode.com/problem/917/description
  3.  
  4. Given a string s, return all palindromic permutations ( without repetitions ). Returns an empty list if there are no palindromic permutations.
  5. sample 1
  6. S = "aabb"  ANSWER-> ["abba","baab"]
  7. sample 2
  8. S = "abc"  ANSWER-> []
  9. */
  10.  
  11.  
  12. ======================================================================================================================
  13.  
  14. class Solution {
  15. public:
  16.     void generate(string str, int curr, vector<string> &res){
  17.         if(str.size()==curr){
  18.             res.push_back(str);
  19.             return;
  20.         }
  21.         for(int i=curr;i<str.size();i++){
  22.             if(i!=curr && str[i]==str[curr]){
  23.                 continue;
  24.             }
  25.             swap(str[i],str[curr]);
  26.             generate(str,curr+1,res);
  27.         }
  28.     }
  29.  
  30.     vector<string> generatePalindromes(string &s) {
  31.         int freq[26]={0};
  32.         for(auto x: s){
  33.             freq[x-'a']++;
  34.         }
  35.         int odd=0;
  36.         char midChar='#';
  37.         for(int i=0;i<26;i++){
  38.             if(freq[i]%2!=0){
  39.                 midChar=(i+'a');
  40.                 odd++;
  41.             }
  42.         }
  43.         if(odd>1){
  44.             return {};
  45.         }
  46.         string str="";
  47.         for(int i=0;i<26;i++){
  48.             int f=freq[i]/2;
  49.             while(f--){
  50.                 str+=(i+'a');
  51.             }
  52.         }
  53.         vector<string> res;
  54.         generate(str,0,res);
  55.         for(int i=0;i<res.size();i++){
  56.             string curr=res[i];
  57.             string rev=curr;
  58.             reverse(rev.begin(),rev.end());
  59.             if(midChar!='#'){
  60.                 curr+=midChar;
  61.             }
  62.             res[i]=curr+rev;
  63.         }
  64.         return res;
  65.     }
  66. };
Advertisement
Add Comment
Please, Sign In to add comment