Check if a string can be rearranged to form special palindrome in Python

PythonServer Side ProgrammingProgramming

Suppose we have a string; we have to check whether characters of the given string can be shuffled to make a palindrome or not.

So, if the input is like s = "aarcrce", then the output will be True as we can shuffle characters to form "racecar" which is a palindrome.

To solve this, we will follow these steps −

  • size := 256
  • freq := an array of size 256 and fill with 0
  • for i in range 0 to size of s, do
    • increse frequency of character s[i] in freq array by 1
  • odd_count := 0
  • for i in range 0 to size, do
    • if freq[i] is idd, then
      • odd_count := odd_count + 1
    • if odd_count > 1, then
      • return False
  • return True

Let us see the following implementation to get better understanding −

Example

 Live Demo

size = 256
def solve(s) :
   freq = [0] * size
   for i in range( 0, len(s)) :
      freq[ord(s[i])] = freq[ord(s[i])] + 1
   odd_count = 0
   for i in range(0, size) :
      if freq[i] % 2 == 1 :
         odd_count = odd_count + 1
      if odd_count > 1:
         return False
   return True
s = "aarcrce"
print(solve(s))

Input

"aarcrce"

Output

True
raja
Published on 29-Dec-2020 17:39:22
Advertisements