Skip to content

Commit 25647e8

Browse files
authored
Create Palindrome Permutation II.py
1 parent a0d1d29 commit 25647e8

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

Palindrome Permutation II.py

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
'''
2+
Given a string s, return all the palindromic permutations (without duplicates) of it. Return an empty list if no palindromic permutation could be form.
3+
4+
Example 1:
5+
6+
Input: "aabb"
7+
Output: ["abba", "baab"]
8+
Example 2:
9+
10+
Input: "abc"
11+
Output: []
12+
13+
'''
14+
15+
class Solution(object):
16+
def generatePalindromes(self, s):
17+
"""
18+
:type s: str
19+
:rtype: List[str]
20+
"""
21+
dic = {}
22+
for c in s:
23+
if c not in dic:
24+
dic[c] = 0
25+
dic[c] += 1
26+
27+
28+
odd_count = 0
29+
odd_c = None
30+
for c in dic:
31+
if dic[c] & 1:
32+
odd_count += 1
33+
dic[c] -= 1
34+
odd_c = c
35+
36+
if odd_count > 1:
37+
return []
38+
39+
tmp = ''
40+
if odd_count == 1:
41+
tmp = odd_c
42+
43+
res = set()
44+
self.find(dic, len(s), tmp, res)
45+
return list(res)
46+
47+
def find(self, dic, length, tmp, res):
48+
if len(tmp) == length:
49+
res.add(tmp)
50+
return
51+
52+
for c in dic:
53+
if dic[c] == 0:
54+
continue
55+
56+
dic[c] -= 2
57+
self.find(dic, length, c + tmp + c, res)
58+
59+
dic[c] += 2
60+
61+
62+

0 commit comments

Comments
 (0)