267 Palindrome Permutation II
Given a strings
, return all the palindromic permutations (without duplicates) of it. Return an empty list if no palindromic permutation could be form.
For example:
Givens = "aabb"
, return["abba", "baab"]
.
Givens = "abc"
, return[]
.
The Idea: This algorithm take ideas from two different concepts and combines them. First: how can we accurately define what is palindromic? A palindrome has some [baseStr] + [midElement] + [reverse(baseStr)]
. Note that both baseStr
and midElement
can be the empty string, so this definition follows true for both even and odd length strings. We can identify these components by counting the occurrences of s
into a hash table. There can only be ever a single instance (at most) of an odd frequency (from which 1 it's elements has to be within the center of the string), otherwise s can not be a palindrome. There can be 0 or more instances of an even frequency.
Second: once these components are identified, we can then generate all the permutations of baseStr
, and append to a solution vector for [baseStr] + [midElement] + [reverse(baseStr)]
Complexity: O(n!) time and O(|unique(s)|) extra space
Last updated