Skip to content
Advertisement

How to check if permutation of a string is a palindrome

Im new to python and im trying to check if any permutation of a string is a palindrome. Here is my code:

JavaScript

The problem I am having is that it I dont want my set to include spaces or any puncuation thats in the string. Is there any way to only check the letters? For example, the string “Mr. owl ate my Metal worm” shouldnt use the period or spaces when checking if it is a palindrome.

Advertisement

Answer

You can certainly check all permutations, but there is a much more efficient approach.

Note that in order for a string to be a palindrome, then every letter is mirrored around the center of the string. That means a collection of letters can form a palindrome if there is at most one letter that has an odd count.

Here is how you can implement this:

The first step is to convert the string to lower case and remove the nonalpha characters (like spaces and punctuation). We can do that by using a list comprehension to iterate over each character in the string and keep only those where str.isalpha() returns True.

JavaScript

Next count each letter. You can use collections.Counter for this:

JavaScript

Finally count the number of letters that have an odd count. If the count is 0 or 1, a palindrome must be possible.

JavaScript

Putting that all together, you can make a function:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement