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