
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Longest Palindrome by Removing or Shuffling Chars 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 −
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