Trova il palindromo più lungo formato rimuovendo o mescolando i caratteri dalla stringa

Data una stringa, trovare il palindromo più lungo che può essere costruito rimuovendo o mescolando i caratteri dalla stringa. Restituisce solo un palindromo se sono presenti più stringhe palindrome di lunghezza maggiore.

Esempi: 

  Input:    abc   Output:   a OR b OR c   Input:    aabbcc   Output:   abccba OR baccab OR cbaabc OR any other palindromic string of length 6.   Input:    abbaccd   Output:   abcdcba OR ...   Input:    aba   Output:   aba 

Possiamo dividere qualsiasi corda palindromica in tre parti: inizio metà e fine. Per una stringa palindromica di lunghezza dispari, ad esempio 2n + 1 'beg' è composto dai primi n caratteri della stringa, 'mid' sarà composto da solo 1 carattere, ovvero (n + 1)esimo carattere e 'end' sarà composto dagli ultimi n caratteri della stringa palindromica. Per stringhe palindromiche di lunghezza pari 2n 'mid' sarà sempre vuoto. Va notato che 'end' sarà l'inverso di 'beg' affinché la stringa sia palindroma.

L'idea è di utilizzare l'osservazione di cui sopra nella nostra soluzione. Poiché è consentito lo spostamento dei caratteri, l'ordine dei caratteri non ha importanza nella stringa di input. Per prima cosa otteniamo la frequenza di ciascun carattere nella stringa di input. Quindi tutti i caratteri che hanno un'occorrenza pari (diciamo 2n) nella stringa di input faranno parte della stringa di output poiché possiamo facilmente inserire n caratteri nella stringa 'beg' e gli altri n caratteri nella stringa 'end' (preservando l'ordine palindromo). Per i caratteri che hanno occorrenze dispari (diciamo 2n + 1) riempiamo 'mid' con uno di tutti questi caratteri. e i restanti 2n caratteri vengono divisi a metà e aggiunti all'inizio e alla fine.

Di seguito è riportata l'implementazione dell'idea di cui sopra 

C++
   // C++ program to find the longest palindrome by removing   // or shuffling characters from the given string   #include          using     namespace     std  ;   // Function to find the longest palindrome by removing   // or shuffling characters from the given string   string     findLongestPalindrome  (  string     str  )   {      // to stores freq of characters in a string      int     count  [  256  ]     =     {     0     };      // find freq of characters in the input string      for     (  int     i     =     0  ;     i      <     str  .  size  ();     i  ++  )      count  [  str  [  i  ]]  ++  ;      // Any palindromic string consists of three parts      // beg + mid + end      string     beg     =     ''       mid     =     ''       end     =     ''  ;      // solution assumes only lowercase characters are      // present in string. We can easily extend this      // to consider any set of characters      for     (  char     ch     =     'a'  ;     ch      <=     'z'  ;     ch  ++  )      {      // if the current character freq is odd      if     (  count  [  ch  ]     &     1  )      {      // mid will contain only 1 character. It      // will be overridden with next character      // with odd freq      mid     =     ch  ;      // decrement the character freq to make      // it even and consider current character      // again      count  [  ch  --  ]  --  ;      }      // if the current character freq is even      else      {      // If count is n(an even number) push      // n/2 characters to beg string and rest      // n/2 characters will form part of end      // string      for     (  int     i     =     0  ;     i      <     count  [  ch  ]  /  2     ;     i  ++  )      beg  .  push_back  (  ch  );      }      }      // end will be reverse of beg      end     =     beg  ;      reverse  (  end  .  begin  ()     end  .  end  ());      // return palindrome string      return     beg     +     mid     +     end  ;   }   // Driver code   int     main  ()   {      string     str     =     'abbaccd'  ;      cout      < <     findLongestPalindrome  (  str  );      return     0  ;   }   
Java
   // Java program to find the longest palindrome by removing   // or shuffling characters from the given string   class   GFG     {   // Function to find the longest palindrome by removing   // or shuffling characters from the given string      static     String     findLongestPalindrome  (  String     str  )     {      // to stores freq of characters in a string      int     count  []     =     new     int  [  256  ]  ;      // find freq of characters in the input string      for     (  int     i     =     0  ;     i      <     str  .  length  ();     i  ++  )     {      count  [  str  .  charAt  (  i  )  ]++  ;      }      // Any palindromic string consists of three parts      // beg + mid + end      String     beg     =     ''       mid     =     ''       end     =     ''  ;      // solution assumes only lowercase characters are      // present in string. We can easily extend this      // to consider any set of characters      for     (  char     ch     =     'a'  ;     ch      <=     'z'  ;     ch  ++  )     {      // if the current character freq is odd      if     (  count  [  ch  ]     %     2     ==     1  )     {      // mid will contain only 1 character. It      // will be overridden with next character      // with odd freq      mid     =     String  .  valueOf  (  ch  );      // decrement the character freq to make      // it even and consider current character      // again      count  [  ch  --]--  ;      }     // if the current character freq is even      else     {      // If count is n(an even number) push      // n/2 characters to beg string and rest      // n/2 characters will form part of end      // string      for     (  int     i     =     0  ;     i      <     count  [  ch  ]     /     2  ;     i  ++  )     {      beg     +=     ch  ;      }      }      }      // end will be reverse of beg      end     =     beg  ;      end     =     reverse  (  end  );      // return palindrome string      return     beg     +     mid     +     end  ;      }      static     String     reverse  (  String     str  )     {      // convert String to character array       // by using toCharArray       String     ans     =     ''  ;      char  []     try1     =     str  .  toCharArray  ();      for     (  int     i     =     try1  .  length     -     1  ;     i     >=     0  ;     i  --  )     {      ans     +=     try1  [  i  ]  ;      }      return     ans  ;      }      // Driver code      public     static     void     main  (  String  []     args  )     {      String     str     =     'abbaccd'  ;      System  .  out  .  println  (  findLongestPalindrome  (  str  ));      }   }   // This code is contributed by PrinciRaj1992   
Python3
   # Python3 program to find the longest palindrome by removing   # or shuffling characters from the given string   # Function to find the longest palindrome by removing   # or shuffling characters from the given string   def   findLongestPalindrome  (  strr  ):   # to stores freq of characters in a string   count   =   [  0  ]  *  256   # find freq of characters in the input string   for   i   in   range  (  len  (  strr  )):   count  [  ord  (  strr  [  i  ])]   +=   1   # Any palindromic consists of three parts   # beg + mid + end   beg   =   ''   mid   =   ''   end   =   ''   # solution assumes only lowercase characters are   # present in string. We can easily extend this   # to consider any set of characters   ch   =   ord  (  'a'  )   while   ch    <=   ord  (  'z'  ):   # if the current character freq is odd   if   (  count  [  ch  ]   &   1  ):   # mid will contain only 1 character. It   # will be overridden with next character   # with odd freq   mid   =   ch   # decrement the character freq to make   # it even and consider current character   # again   count  [  ch  ]   -=   1   ch   -=   1   # if the current character freq is even   else  :   # If count is n(an even number) push   # n/2 characters to beg and rest   # n/2 characters will form part of end   # string   for   i   in   range  (  count  [  ch  ]  //  2  ):   beg   +=   chr  (  ch  )   ch   +=   1   # end will be reverse of beg   end   =   beg   end   =   end  [::  -  1  ]   # return palindrome string   return   beg   +   chr  (  mid  )   +   end   # Driver code   strr   =   'abbaccd'   print  (  findLongestPalindrome  (  strr  ))   # This code is contributed by mohit kumar 29   
C#
   // C# program to find the longest    // palindrome by removing or   // shuffling characters from    // the given string   using     System  ;   class     GFG   {      // Function to find the longest       // palindrome by removing or       // shuffling characters from       // the given string      static     String     findLongestPalindrome  (  String     str  )         {      // to stores freq of characters in a string      int     []  count     =     new     int  [  256  ];      // find freq of characters       // in the input string      for     (  int     i     =     0  ;     i      <     str  .  Length  ;     i  ++  )         {      count  [  str  [  i  ]]  ++  ;      }      // Any palindromic string consists of       // three parts beg + mid + end      String     beg     =     ''       mid     =     ''       end     =     ''  ;      // solution assumes only lowercase       // characters are present in string.      // We can easily extend this to       // consider any set of characters      for     (  char     ch     =     'a'  ;     ch      <=     'z'  ;     ch  ++  )             {      // if the current character freq is odd      if     (  count  [  ch  ]     %     2     ==     1  )         {          // mid will contain only 1 character.       // It will be overridden with next       // character with odd freq      mid     =     String  .  Join  (  ''    ch  );      // decrement the character freq to make      // it even and consider current       // character again      count  [  ch  --  ]  --  ;      }             // if the current character freq is even      else         {          // If count is n(an even number) push      // n/2 characters to beg string and rest      // n/2 characters will form part of end      // string      for     (  int     i     =     0  ;     i      <     count  [  ch  ]     /     2  ;     i  ++  )         {      beg     +=     ch  ;      }      }      }      // end will be reverse of beg      end     =     beg  ;      end     =     reverse  (  end  );      // return palindrome string      return     beg     +     mid     +     end  ;      }      static     String     reverse  (  String     str  )         {      // convert String to character array       // by using toCharArray       String     ans     =     ''  ;      char  []     try1     =     str  .  ToCharArray  ();      for     (  int     i     =     try1  .  Length     -     1  ;     i     >=     0  ;     i  --  )         {      ans     +=     try1  [  i  ];      }      return     ans  ;      }      // Driver code      public     static     void     Main  ()         {      String     str     =     'abbaccd'  ;      Console  .  WriteLine  (  findLongestPalindrome  (  str  ));      }   }   // This code is contributed by 29AjayKumar   
JavaScript
    <  script  >   // Javascript program to find the    // longest palindrome by removing   // or shuffling characters from    // the given string   // Function to find the longest    // palindrome by removing   // or shuffling characters from   // the given string      function     findLongestPalindrome  (  str  )      {      // to stores freq of characters       // in a string      let     count     =     new     Array  (  256  );      for  (  let     i  =  0  ;  i   <  256  ;  i  ++  )      {      count  [  i  ]  =  0  ;      }          // find freq of characters in       // the input string      for     (  let     i     =     0  ;     i      <     str  .  length  ;     i  ++  )     {      count  [  str  [  i  ].  charCodeAt  (  0  )]  ++  ;      }          // Any palindromic string consists      // of three parts      // beg + mid + end      let     beg     =     ''       mid     =     ''       end     =     ''  ;          // solution assumes only       // lowercase characters are      // present in string.       // We can easily extend this      // to consider any set of characters      for     (  let     ch     =     'a'  .  charCodeAt  (  0  );         ch      <=     'z'  .  charCodeAt  (  0  );     ch  ++  )     {      // if the current character freq is odd      if     (  count  [  ch  ]     %     2     ==     1  )     {      // mid will contain only 1 character. It      // will be overridden with next character      // with odd freq      mid     =     String  .  fromCharCode  (  ch  );          // decrement the character freq to make      // it even and consider current character      // again      count  [  ch  --  ]  --  ;      }     // if the current character freq is even      else     {      // If count is n(an even number) push      // n/2 characters to beg string and rest      // n/2 characters will form part of end      // string      for     (  let     i     =     0  ;     i      <     count  [  ch  ]     /     2  ;     i  ++  )         {      beg     +=     String  .  fromCharCode  (  ch  );      }      }      }          // end will be reverse of beg      end     =     beg  ;      end     =     reverse  (  end  );          // return palindrome string      return     beg     +     mid     +     end  ;      }          function     reverse  (  str  )      {      // convert String to character array       // by using toCharArray       let     ans     =     ''  ;      let     try1     =     str  .  split  (  ''  );          for     (  let     i     =     try1  .  length     -     1  ;     i     >=     0  ;     i  --  )     {      ans     +=     try1  [  i  ];      }      return     ans  ;      }          // Driver code      let     str     =     'abbaccd'  ;      document  .  write  (  findLongestPalindrome  (  str  ));          // This code is contributed by unknown2108        <  /script>   

Produzione
abcdcba 

Complessità temporale della soluzione precedente è O(n) dove n è la lunghezza della stringa. Poiché il numero di caratteri dell'alfabeto è costante, non contribuiscono all'analisi asintotica.
Spazio ausiliario utilizzato dal programma è M dove M è il numero di caratteri ASCII.