Find longest palindrome formed by removing or shuffling chars from string in Python


Suppose we have a string; we have to find the longest palindrome that can be generated by deleting or shuffling the characters from the string. And if there are more than one palindrome then return only one.

So, if the input is like pqqprrs, then the output will be pqrsrqp.

  • To solve this, we will follow these steps −

  • count := array of size 256, filled with 0

  • for i in range 0 to size of string, do

    • count[ASCII of(string[i]) ] := count[ASCII of(string[i]) ] + 1

  • begin := blank string, mid := blank string, end := blank string

  • character := ASCII of('a')

  • while character <= ASCII of('z') , do

    • if count[character] AND 1 is non-zero, then

      • mid := character

      • count[character] := count[character] - 1

      • character := character - 1

    • otherwise,

      • for i in range 0 to count[character]/2 (integer division), do

        • begin := begin + character from (character)

    • character := character + 1

  • end := begin

  • end := reverse end

  • return begin concatenate character from (mid) concatenate end

Example

Let us see the following implementation to get better understanding −

 Live Demo

def get_palindrome(string):
   count = [0]*256
   for i in range(len(string)):
      count[ord(string[i])] += 1
   begin = ""
   mid = ""
   end = ""
   character = ord('a')
   while character <= ord('z'):
      if (count[character] & 1):
         mid = character
         count[character] -= 1
         character -= 1
      else:
         for i in range(count[character]//2):
            begin += chr(character)
      character += 1
   end = begin
   end = end[::-1]
   return begin + chr(mid) + end
string = "pqqprrs"
print(get_palindrome(string))

Input

"pqqprrs"

Output

pqrsrqp

Updated on: 25-Aug-2020

182 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements