Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- link- https://www.lintcode.com/problem/917/description
- Given a string s, return all palindromic permutations ( without repetitions ). Returns an empty list if there are no palindromic permutations.
- sample 1
- S = "aabb" ANSWER-> ["abba","baab"]
- sample 2
- S = "abc" ANSWER-> []
- */
- ======================================================================================================================
- class Solution {
- public:
- void generate(string str, int curr, vector<string> &res){
- if(str.size()==curr){
- res.push_back(str);
- return;
- }
- for(int i=curr;i<str.size();i++){
- if(i!=curr && str[i]==str[curr]){
- continue;
- }
- swap(str[i],str[curr]);
- generate(str,curr+1,res);
- }
- }
- vector<string> generatePalindromes(string &s) {
- int freq[26]={0};
- for(auto x: s){
- freq[x-'a']++;
- }
- int odd=0;
- char midChar='#';
- for(int i=0;i<26;i++){
- if(freq[i]%2!=0){
- midChar=(i+'a');
- odd++;
- }
- }
- if(odd>1){
- return {};
- }
- string str="";
- for(int i=0;i<26;i++){
- int f=freq[i]/2;
- while(f--){
- str+=(i+'a');
- }
- }
- vector<string> res;
- generate(str,0,res);
- for(int i=0;i<res.size();i++){
- string curr=res[i];
- string rev=curr;
- reverse(rev.begin(),rev.end());
- if(midChar!='#'){
- curr+=midChar;
- }
- res[i]=curr+rev;
- }
- return res;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment